區間最小值 線段樹 (2015年 JXNU_ACS 算法組暑假第一次周賽)
阿新 • • 發佈:2017-05-29
找到 img 這不 pos line roi ssi input article
接下去一行給出n個數字,代表數字序列。
Statistic | Submit | Back
區間最小值
Time Limit : 3000/1000ms (Java/Other) Memory Limit : 65535/32768K (Java/Other)
Total Submission(s) : 12 Accepted Submission(s) : 5
Font: Times New Roman | Verdana | Georgia
Font Size: ← →
Problem Description
給定一個數字序列,查詢隨意給定區間內數字的最小值。Input
輸入包括多組測試用例,每組測試用例的開頭為一個整數n(1<=n<=100000)。代表數字序列的長度。接下去一行給出n個數字,代表數字序列。
數字在int範圍內。
下一行為一個整數t(1<=t<=10000),代表查詢的次數。
最後t行,每行給出一個查詢。由兩個整數表示l、r(1<=l<=r<=n)。
Output
對於每一個查詢,輸出區間[l,r]內的最小值。Sample Input
5 3 2 1 4 3 3 1 3 2 4 4 5
Sample Output
1 1 3
Author
吳迎Statistic | Submit | Back
線段樹問題。感覺這是最美的數據結構~
非常基礎的線段樹問題。對於這不懂的還是多多百度呀。
#include <stdio.h> #include <algorithm> using namespace std; int num[100005]; struct node { int left,right,val;//每一個節點有三個值,左區間,右區間,和最小值 }c[100005*4]; void build_tree(int l,int r,int root)//建樹 { c[root].left=l; c[root].right=r; if(l==r)//假設左區間等於右區間就賦值 { c[root].val=num[l]; return ; } int mid=(l+r)/2; build_tree(l,mid,root*2); build_tree(mid+1,r,root*2+1); c[root].val=min(c[root*2].val,c[root*2+1].val);//遞歸得到 } void find_tree(int l,int r,int &min1,int root)//查找 { if(c[root].left==l&&c[root].right==r) { min1=c[root].val; return ; } int mid=(c[root].left+c[root].right)/2; if(mid<l)//先找到所要尋找的區間在樹上的區間範圍 find_tree(l,r,min1,root*2+1); else if(mid>=r) find_tree(l,r,min1,root*2); else//找到了所要找的區間 { int min2; find_tree(l,mid,min1,root*2);//左兒子一個最小值 find_tree(mid+1,r,min2,root*2+1);//右兒子一個最小值 min1=min(min1,min2);//選最小的 } } int main() { int n,k; while(scanf("%d",&n)!=EOF) { for(int i=1;i<=n;i++) scanf("%d",&num[i]); build_tree(1,n,1); scanf("%d",&k); while(k--) { int a,b,min1; scanf("%d %d",&a,&b); find_tree(a,b,min1,1); printf("%d\n",min1); } } return 0; }
區間最小值 線段樹 (2015年 JXNU_ACS 算法組暑假第一次周賽)