标签:
Time Limit: 12000MS | Memory Limit: 65536K | |
Total Submissions: 48608 | Accepted: 14047 | |
Case Time Limit: 5000MS |
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 <stdio.h> 2 #include <string.h> 3 #include <queue> 4 #include <algorithm> 5 using namespace std; 6 7 int a[1000005],q[1000005],p[1000005],mi[1000005],ma[1000005]; 8 int n,k; 9 10 void get_min() 11 { 12 int i,j; 13 int head=1,tail=0; 14 for(i=0;i<k-1;i++) 15 { 16 while(head<=tail && q[tail]>=a[i]) 17 tail--; 18 q[++tail]=a[i]; 19 p[tail]=i; 20 } 21 22 for(;i<n;i++) 23 { 24 while(head<=tail && q[tail]>=a[i]) 25 tail--; 26 q[++tail]=a[i]; 27 p[tail]=i; 28 while(p[head]<i-k+1) 29 { 30 head++; 31 } 32 mi[i-k+1]=q[head]; 33 } 34 } 35 36 void get_max() 37 { 38 int i,j; 39 int head=1,tail=0; 40 for(i=0;i<k-1;i++) 41 { 42 while(head<=tail && q[tail]<=a[i]) 43 tail--; 44 q[++tail]=a[i]; 45 p[tail]=i; 46 } 47 for(;i<n;i++) 48 { 49 while(head<=tail && q[tail]<=a[i]) 50 tail--; 51 q[++tail]=a[i]; 52 p[tail]=i; 53 while(p[head]<i-k+1) 54 head++; 55 ma[i-k+1]=q[head]; 56 } 57 } 58 59 int main() 60 { 61 int i,j; 62 scanf("%d %d",&n,&k); 63 for(i=0;i<n;i++) 64 { 65 scanf("%d",&a[i]); 66 } 67 get_max(); 68 get_min(); 69 for(i=0;i<n-k;i++) 70 { 71 printf("%d ",mi[i]); 72 } 73 printf("%d\n",mi[n-k]); 74 for(i=0;i<n-k;i++) 75 { 76 printf("%d ",ma[i]); 77 } 78 printf("%d\n",ma[n-k]); 79 return 0; 80 }
标签:
原文地址:http://www.cnblogs.com/cyd308/p/4817598.html