E/C

来源:互联网 发布:微商拍小视频软件 编辑:程序博客网 时间:2024/05/29 14:02

用了一个单调队列,还有注意printf


An array of size n ≤ 10 6 is given to you. There is a sliding window of size kwhich is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves rightwards by one position. Following is an example: 
The array is [1 3 -1 -3 5 3 6 7], and k is 3.Window positionMinimum valueMaximum value[1  3  -1] -3  5  3  6  7 -13 1 [3  -1  -3] 5  3  6  7 -33 1  3 [-1  -3  5] 3  6  7 -35 1  3  -1 [-3  5  3] 6  7 -35 1  3  -1  -3 [5  3  6] 7 36 1  3  -1  -3  5 [3  6  7]37

Your task is to determine the maximum and minimum values in the sliding window at each position. 

Input
The input consists of two lines. The first line contains two integers n and k which are the lengths of the array and the sliding window. There are n integers in the second line. 
Output
There are two lines in the output. The first line gives the minimum values in the window at each position, from left to right, respectively. The second line gives the maximum values. 
Sample Input
8 31 3 -1 -3 5 3 6 7
Sample Output
-1 -3 -3 -3 3 33 3 5 5 6 7


这个题哟,有毒,printf 和cout ,cout输出会导致超时

#include<cstdio>#include<cstring>#include<iostream>using namespace std;const int maxn = 1000005;int n,k;struct node{    int pos,val;}q[maxn];int num[maxn];int Min[maxn];int Max[maxn];void getMin(){   int head=1,tail=0;   for(int i=1;i<k;i++)   {       while(head<=tail&&num[i]<q[tail].val) tail--;       tail++;       q[tail].val=num[i];       q[tail].pos=i;   }   for(int i=k;i<=n;i++)   {       while(head<=tail&&num[i]<q[tail].val) tail--;       tail++;       q[tail].val=num[i];       q[tail].pos=i;       while(i-q[head].pos>=k) head++;       Min[i-k]=q[head].val;   }}void getMax(){    int head=1,tail=0;   for(int i=1;i<k;i++)   {       while(head<=tail&&num[i]>q[tail].val) tail--;       tail++;       q[tail].val=num[i];       q[tail].pos=i;   }   for(int i=k;i<=n;i++)   {       while(head<=tail&&num[i]>q[tail].val) tail--;       tail++;       q[tail].val=num[i];       q[tail].pos=i;      while(q[head].pos<=i-k) head++;       Max[i-k]=q[head].val;   }}int main(){    scanf("%d%d",&n,&k);    for (int i = 1; i <= n; i++)      cin>>num[i];   getMin();   for(int i=0;i<n-k;i++)    printf("%d ",Min[i]);   cout<<Min[n-k]<<endl;   getMax();     for(int i=0;i<n-k;i++)    printf("%d ",Max[i]);   cout<<Max[n-k]<<endl;    return 0;}


ps:

cout是有缓冲输出: 
cout < < "abc " < <endl;
或cout < < "abc\n ";cout < <flush; 这两个才是一样的.
endl相当于输出回车后,再强迫缓冲输出。
flush立即强迫缓冲输出。
printf是无缓冲输出。有输出时立即输出。
结论:
当输出数据量比较大时,printf 比 cout 有更快的速度

0 0
原创粉丝点击