星期天打的网络赛,虽然没我什么事(┬_┬)感觉差距好大。。。这个学期再不能贪玩了,好好学ACM,争取不拉队友的后腿。这道题是一道线段树的裸题,并没有什么好讲的,写个题解留个纪念。。
The Water Problem
Time Limit: 1500/1000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)
Total Submission(s): 574 Accepted Submission(s): 460
Problem Description
In Land waterless, water is a very limited resource. People always fight for the biggest source of water. Given a sequence of water sources with a1,a2,a3,...,anrepresenting the size of the water source. Given a set of queries each containing 2 integers l and r, please find out the biggest water source between al and ar.
Input
First you are given an integer T(T≤10) indicating the number of test cases. For each test case, there is a number n(0≤n≤1000) on a line representing the number of water sources. n integers follow, respectively a1,a2,a3,...,an, and each integer is in {1,...,106}. On the next line, there is a number q(0≤q≤1000) representing the number of queries. After that, there will be q lines with two integers l and r(1≤l≤r≤n) indicating the range of which you should find out the biggest water source.
Output
For each query, output an integer representing the size of the biggest water source.
Sample Input
3
1
100
1
1 1
5
1 2 3 4 5
5
1 2
1 3
2 4
3 4
3 5
3
1 999999 1
4
1 1
1 2
2 3
3 3
Sample Output
100 2 3 4 4 5 1 999999 999999 1
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<algorithm> 5 using namespace std; 6 #define INF 0x7fffffff 7 int maxv=-INF; 8 struct node 9 { 10 int l,r; 11 int maxv; 12 int mid() 13 { 14 return (l+r)/2; 15 } 16 }tree[800020]; 17 void buildtree(int root,int l,int r) 18 { 19 tree[root].l=l; 20 tree[root].r=r; 21 tree[root].maxv=-INF; 22 if(l!=r) 23 { 24 buildtree(2*root+1,l,(l+r)/2); 25 buildtree(2*root+2,(l+r)/2+1,r); 26 } 27 } 28 void insert(int root,int i,int v) 29 { 30 if(tree[root].l==tree[root].r) 31 { 32 tree[root].maxv=v; 33 return; 34 } 35 tree[root].maxv=max(tree[root].maxv,v); 36 if(i<=tree[root].mid()) 37 insert(root*2+1,i,v); 38 else 39 insert(root*2+2,i,v); 40 } 41 void query(int root,int s,int e) 42 { 43 if(maxv>=tree[root].maxv) 44 return; 45 if(tree[root].l==s&&tree[root].r==e) 46 { 47 maxv=max(tree[root].maxv,maxv); 48 return; 49 } 50 if(e<=tree[root].mid()) 51 query(2*root+1,s,e); 52 else if(s>tree[root].mid()) 53 query(2*root+2,s,e); 54 else 55 { 56 query(2*root+1,s,tree[root].mid()); 57 query(2*root+2,tree[root].mid()+1,e); 58 } 59 } 60 int main() 61 { 62 int T,n,m,i,j; 63 cin>>T; 64 while(T--) 65 { 66 cin>>n; 67 buildtree(0,1,n); 68 for(i=1;i<=n;i++) 69 { 70 int h; 71 cin>>h; 72 insert(0,i,h); 73 } 74 cin>>m; 75 for(i=0;i<m;i++) 76 { 77 int s,e; 78 cin>>s>>e; 79 maxv=-INF; 80 query(0,s,e); 81 printf("%d ",maxv); 82 } 83 } 84 return 0; 85 }