您的位置:首页 > 其它

51nod 1349 最大值(单调栈)

2017-10-03 15:14 369 查看
http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1349

题意:

求区间内最大值大于等于k的区间个数。

思路:

利用求出对于以a[i]为最大值的区间范围,pre[i]表示左端范围,aft[i]表示右端范围,则区间个数为$(i-pre[i]+1)*(aft[i]-i+1)$。

#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdio>
#include<vector>
#include<stack>
#include<queue>
#include<cmath>
#include<map>
#include<set>
using namespace std;
typedef long long ll;
typedef pair<int,int> pll;
const int INF = 0x3f3f3f3f;
const int maxn = 100000+5;

int n;
int a[maxn];
int sta[maxn];
ll ans[maxn];

ll pre[maxn],aft[maxn];

inline int read()
{
int x=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
return x*f;
}

int main()
{
//freopen("in.txt","r",stdin);
while(~scanf("%d",&n))
{
for(int i=1;i<=n;i++)  a[i]=read();
int top = 0;
for(int i=1;i<=n;i++)
{
while(top && a[sta[top]]<=a[i])  top--;
if(top==0)  pre[i]=1;
else pre[i]=sta[top]+1;
sta[++top]=i;
}
top=0;
for(int i=n;i>=1;i--)
{
while(top && a[sta[top]]<a[i])  top--;  //这儿特别注意一下
if(top==0)  aft[i]=n;
else aft[i]=sta[top]-1;
sta[++top]=i;
}
memset(ans,0,sizeof(ans));
for(int i=1;i<=n;i++)  ans[a[i]]+=(i-pre[i]+1)*(aft[i]-i+1);
for(int i=100000;i>=1;i--)  ans[i]+=ans[i+1];
int q; q=read();
while(q--)
{
int x; x=read();
printf("%lld\n",ans[x]);
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: