1290A - Mind Control (区间最值)
Solution:
O(n2):
1 #include <bits/stdc++.h> 2 # define LL long long 3 using namespace std; 4 const int INF=0x7fffffff; 5 int n, m, k; 6 int arr[3510]; 7 int b[3510]; 8 int main(){ 9 int T; 10 scanf("%d", &T); 11 while(T--){ 12 scanf("%d %d %d", &n, &m, &k); 13 for(int i=1;i<=n;++i){ 14 scanf("%d", arr+i); 15 } 16 17 k=min(k,m-1); 18 for(int i=0;i<=m-1;++i){ 19 b[i]=max(arr[i+1],arr[i+1+n-m]); 20 } 21 22 int ans=0; 23 for(int x=0;x<=k;++x){ 24 int localmin=INF; 25 for(int xaddy=x;xaddy<=x+m-1-k;++xaddy){ 26 localmin=min(localmin,b[xaddy]); 27 } 28 ans=max(ans,localmin); 29 } 30 printf("%d\n", ans); 31 } 32 return 0; 33 }
Segment Tree:
1 #include <bits/stdc++.h> 2 # define LL long long 3 using namespace std; 4 const int INF=0x7fffffff; 5 int n, m, k; 6 int arr[3510]; 7 int b[3510]; 8 int seg[3510<<2]; 9 10 void build(int idx, int left, int right){ 11 if(left==right){ 12 seg[idx]=b[left]; 13 return; 14 } 15 int mid=(left+right)>>1; 16 build(idx*2+1,left,mid); 17 build(idx*2+2,mid+1,right); 18 seg[idx]=min(seg[idx*2+1],seg[idx*2+2]); 19 } 20 21 int query(int idx, int qleft, int qright, int left, int right){ 22 if(qleft>right || qright<left) return INF; 23 if(qleft<=left && qright>=right){ 24 return seg[idx]; 25 } 26 27 int mid=(left+right)>>1; 28 int res=INF; 29 int t1=query(idx*2+1,qleft,qright,left,mid); 30 int t2=query(idx*2+2,qleft,qright,mid+1,right); 31 res=min(res,min(t1,t2)); 32 return res; 33 } 34 35 int main(){ 36 int T; 37 scanf("%d", &T); 38 while(T--){ 39 memset(seg,127,sizeof(seg)); 40 scanf("%d %d %d", &n, &m, &k); 41 for(int i=1;i<=n;++i){ 42 scanf("%d", arr+i); 43 } 44 45 k=min(k,m-1); 46 for(int i=0;i<=m-1;++i){ 47 b[i]=max(arr[i+1],arr[i+1+n-m]); 48 } 49 build(0,0,m-1); 50 int ans=0; 51 int xaddy=0; 52 for(int x=0;x<=k;++x){ 53 int localmin=query(0,x,x+m-1-k, 0,m-1); 54 ans=max(ans,localmin); 55 } 56 printf("%d\n", ans); 57 } 58 return 0; 59 }
Deque:
1 #include <bits/stdc++.h> 2 # define LL long long 3 using namespace std; 4 const int INF=0x7fffffff; 5 int n, m, k; 6 int arr[3510]; 7 int b[3510]; 8 int main(){ 9 int T; 10 scanf("%d", &T); 11 while(T--){ 12 scanf("%d %d %d", &n, &m, &k); 13 for(int i=1;i<=n;++i){ 14 scanf("%d", arr+i); 15 } 16 17 k=min(k,m-1); 18 for(int i=0;i<=m-1;++i){ 19 b[i]=max(arr[i+1],arr[i+1+n-m]); 20 } 21 deque<int> q; 22 int ans=0; 23 int xaddy=0; 24 for(int x=0;x<=k;++x){ 25 while(q.size()>0 && q.front()<x) q.pop_front(); 26 27 while(xaddy<=x+m-1-k){ 28 while(q.size()>0 && b[xaddy]<=b[q.back()]){ 29 q.pop_back(); 30 } 31 q.push_back(xaddy); 32 ++xaddy; 33 } 34 ans=max(ans,b[q.front()]); 35 } 36 printf("%d\n", ans); 37 } 38 return 0; 39 }