The array is [1 3 -1 -3 5 3 6 7], and k is 3.
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.
8 3 1 3 -1 -3 5 3 6 7
-1 -3 -3 -3 3 3 3 3 5 5 6 7
题意:
从左往右依次k个数字一组,输出每组的最大值,和最小值。
常规的做法超时有没有。
未ac code:
#if 1
#include<iostream>
#include<stdio.h>
#include<cstring>
using namespace std;
const int Max=1e6+10;
int a[Max];
int quee[Max];
int b[Max];
int n,k;
void minn()
{
int tail=1,head=1;
for(int i=0; i<k-1; i++)
{
while(tail>=head&&a[quee[tail]]>=a[i])
{
tail--;
}
tail++;
quee[tail]=i;
}
for(int i=k-1; i<n; i++)
{
while(tail>=head&&a[quee[tail]]>=a[i])
tail--;
tail++;
quee[tail]=i;
while(quee[head]<i-k+1)
{
head++;
}
printf("%d ",a[quee[head]]);
}
printf("\n");
}
void maxx()
{
int tail=1,head=1,l=1;
for(int i=0; i<k-1; i++)
{
while(tail>=head&&a[quee[tail]]<=a[i])
{
tail--;
}
tail++;
quee[tail]=i;
}
for(int i=k-1; i<n; i++)
{
while(tail>=head&&a[quee[tail]]<=a[i])
{
tail--;
}
tail++;
quee[tail]=i;
while(quee[head]<i-k+1)
{
head++;
}
printf("%d ",a[quee[head]]);
}
printf("\n");
}
int main()
{
scanf("%d%d",&n,&k);
for(int i=0; i<n; i++)
scanf("%d",&a[i]);
minn();
maxx();
}
#endif
ac code:
#if 0
#include<iostream>
#include<cstring>
#include<stdio.h>
using namespace std;
const int Max=1000005;
int N,M,a[Max],b[Max],c[Max],d[Max];
void maxx()
{
int i,head,tail,l;
l=0;tail=-1;head=0;
for(i=1;i<=M;i++)
{
while(tail>=0&&a[i]>=b[tail])
tail--;
b[++tail]=a[i];
c[tail]=i;
}
d[l++]=b[0];
for(i=M+1;i<=N;i++)
{
if(c[head]<i-M+1)
head++;
while(tail>=head&&a[i]>=b[tail])
tail--;
b[++tail]=a[i];
c[tail]=i;
d[l++]=b[head];
}
for(i=0;i<l-1;i++)
cout<<d[i]<<" ";
cout<<d[l-1]<<endl;
}
void minn()
{
memset(c,0,sizeof(c));
memset(b,0,sizeof(b));
memset(d,0,sizeof(d));
int i,head,tail,l;
l=0;tail=-1;head=0;
for(i=1;i<=M;i++)
{
while(tail>=0&&a[i]<=b[tail])
tail--;
b[++tail]=a[i];
c[tail]=i;
}
d[l++]=b[0];
for(i=M+1;i<=N;i++)
{
if(c[head]<i-M+1)
head++;
while(tail>=head&&a[i]<=b[tail])
tail--;
b[++tail]=a[i];
c[tail]=i;
d[l++]=b[head];
}
for(i=0;i<l-1;i++)
cout<<d[i]<<" ";
cout<<d[l-1]<<endl;
}
int main()
{
while(cin>>N>>M)
{
for(int i=1;i<=N;i++)
scanf("%d",&a[i]);
minn();
maxx();
}
return 0;
}
#endif