标签:
Description
Window position | Minimum value | Maximum value |
---|---|---|
[1 3 -1] -3 5 3 6 7 | -1 | 3 |
1 [3 -1 -3] 5 3 6 7 | -3 | 3 |
1 3 [-1 -3 5] 3 6 7 | -3 | 5 |
1 3 -1 [-3 5 3] 6 7 | -3 | 5 |
1 3 -1 -3 [5 3 6] 7 | 3 | 6 |
1 3 -1 -3 5 [3 6 7] | 3 | 7 |
Your task is to determine the maximum and minimum values in the sliding window at each position.
Input
Output
Sample Input
8 3 1 3 -1 -3 5 3 6 7
Sample Output
-1 -3 -3 -3 3 3 3 3 5 5 6 7
单调队列
1 #include<cstdio> 2 #include<malloc.h> 3 using namespace std; 4 5 struct node 6 { 7 int val; 8 int pos; 9 }; 10 11 int main() 12 { 13 //freopen("in.txt","r",stdin); 14 int i; 15 int head1,end1,head2,end2; 16 int m,n; 17 while(~scanf("%d%d",&m,&n)) 18 { 19 int *p=(int*)malloc(sizeof(int)*m); 20 int *ans1=(int*)malloc(sizeof(int)*m); 21 int *ans2=(int*)malloc(sizeof(int)*m); 22 node *que1=(node*)malloc(sizeof(node)*m); 23 node *que2=(node*)malloc(sizeof(node)*m); 24 for(i=0;i<m;i++) 25 scanf("%d",&p[i]); 26 head1=head2=1,end1=end2=0; 27 for(i=0;i<m;i++) 28 { 29 node temp; 30 temp.pos=i; 31 temp.val=p[i]; 32 while(end1!=0&&que1[end1].val<p[i]&&head1<=end1) 33 end1--; 34 end1++; 35 que1[end1]=temp; 36 while(end1!=0&&que1[head1].pos<i-n+1&&head1<=end1) 37 head1++; 38 ans1[i]=que1[head1].val; 39 while(end2!=0&&que2[end2].val>p[i]&&head2<=end2) 40 end2--; 41 end2++; 42 que2[end2]=temp; 43 while(end2!=0&&que2[head2].pos<i-n+1&&head2<=end2) 44 head2++; 45 ans2[i]=que2[head2].val; 46 } 47 for(i=n-1;i<m-1;i++) 48 printf("%d ",ans2[i]); 49 printf("%d\n",ans2[i]); 50 for(i=n-1;i<m-1;i++) 51 printf("%d ",ans1[i]); 52 printf("%d\n",ans1[i]); 53 free(ans1),free(ans2),free(que1),free(que2),free(p); 54 } 55 return 0; 56 }
标签:
原文地址:http://www.cnblogs.com/homura/p/4685912.html