Codeforces Global Round 5 D. Balanced Playlist(单调队列)

题目链接
Codeforces Global Round 5 D. Balanced Playlist(单调队列)_第1张图片
Codeforces Global Round 5 D. Balanced Playlist(单调队列)_第2张图片

#include 
using namespace std;
const int maxn=3e5+1;
int n,a[maxn],q[maxn],ans[maxn],vis[maxn],maxx=0,minn=1e9+100;
int main()
{
	scanf("%d",&n);
	for(int i=1;i<=n;++i)
	{
		scanf("%d",&a[i]);
		a[i+2*n]=a[i+n]=a[i];
		minn=min(minn,a[i]);
		maxx=max(maxx,a[i]);
	}
	if(maxx<=2*minn)
	{
		for(int i=1;i<=n;++i) printf("-1 ");
		return 0;
	}
	int first=1,now=0;
	for(int i=1;i<=3*n;++i)
	{
		while(now<=first&&q[first]<a[i]) first--;
		q[++first]=a[i];
		vis[first]=i;
		while(q[now]>a[i]*2)//从前往后遍历队列内的元素 
		ans[vis[now]]=i-vis[now],now++;
	}
	for(int i=3*n;i>=1;--i) if(ans[i]==0) ans[i]=ans[i+1]+1;//队列里有些元素被弹出了,不过可以根据后面的答案来更新前面的
	for(int i=1;i<=n;++i) printf("%d ",ans[i]); 
}

你可能感兴趣的:(单调栈/单调队列)