51 Nod 1349 最大值

                                1349 最大值

有一天,小a给了小b一些数字,让小b帮忙找到其中最大的数,由于小b是一个程序猿,当然写了一个代码很快的解决了这个问题。

这时,邪恶的小c又出现了,他问小b,假如我只需要知道这些数字中的某个区间的最大值,你还能做嘛?

小b经过七七四十九天的思考,终于完美的解决了这道题目,这次,他想也让小c尝尝苦头,于是他问小c,我现在想知道存在多少不同的区间的最大值大于等于k,你还能做吗?

这次,小c犯了难,他来请教身为程序猿的你。

Hint:一个区间指al,al+1,…,ar这一段的数且l<=r,一个区间的最大值指max{al,al+1,…,ar},两个区间不同当且仅当[l1,r1],[l2,r2]中l1不等于l2或r1不等于r2

Input
第一行读入一个正整数n(1<=n<=100000),表示有n个数字。
接下来一行读入n个正整数ai(1<=ai<=100000)
接下来一行一个正整数Q(1<=Q<=100000),表示有Q组询问。
接下来Q行,每行一个正整数k(1<=k<=100000)
Output
Q行,每行一个正整数,表示存在多少区间大于等于k。
Input示例
3
1 2 3
3
1
2
3
Output示例
6
5
3

思路:单调栈 处理处每一个数 作为最大值的区间 的左右端点
   题目要求的是 大于等于 k 的值
   统计数组后缀和
 1 #include <cctype>
 2 #include <cstdio>
 3 
 4 typedef long long LL;
 5 
 6 const int MAXN=100010;
 7 
 8 int n,q;
 9 
10 int a[MAXN],stack[MAXN];
11 
12 LL ans[MAXN],pre[MAXN],nxt[MAXN];
13 
14 inline void read(int&x) {
15     int f=1;register char c=getchar();
16     for(x=0;!isdigit(c);c=='-'&&(f=-1),c=getchar());
17     for(;isdigit(c);x=x*10+c-48,c=getchar());
18     x=x*f;
19 }
20 
21 int hh() {
22     read(n);
23     for(int i=1; i<=n; ++i) read(a[i]);
24     
25     int top=0;
26     for(int i=1; i<=n; ++i) {
27         while(top && a[stack[top]] <= a[i]) --top;
28         if(!top) pre[i]=1;
29         else pre[i]=stack[top]+1;
30         stack[++top]=i;
31     }
32     
33     top=0;
34     for(int i=n; i>=1; --i) {
35         while(top && a[stack[top]] < a[i]) --top;
36         if(!top) nxt[i]=n;
37         else nxt[i]=stack[top]-1;
38         stack[++top]=i;
39     }
40     
41     for(int i=1; i<=n; ++i) ans[a[i]]+=(LL)(i-pre[i]+1)*(nxt[i]-i+1);
42     for(int i=100000; i>=1; --i) ans[i]+=ans[i+1];
43     
44     read(q);
45     int x;
46     while(q--) {
47         read(x);
48         printf("%lld
",ans[x]);
49     }
50     
51     return 0;
52 }
53 
54 int sb=hh();
55 int main(int argc,char**argv) {;}
代码
 
原文地址:https://www.cnblogs.com/whistle13326/p/7742391.html