题目链接:http://poj.org/problem?id=3250
题目大意:给定一个序列,定义ci为从位置i开始后面连续的严格小于它的个数,最后求ci的总和(1<=i<=n)
解题思路:栈的应用,将每个数压入栈,如果碰到大于栈头的数就退栈,并计算ci,ci就是两个下标想减的值,也可以这样理解,即区间内小于两端的个数。
测试数据:
6
10 3 7 4 12 2
6
4 2 6 3 1 510
2 3 4 5 6 7 8 9 10 1
8
8 7 6 5 4 3 2 1
9
5 8 9 2 3 1 7 4 6
代码:
#include <stdio.h>
#include <string.h>
#define MAX 81000
struct node {
int in,val;
}arr[MAX];
int n,head,tail;
node qu[MAX];
__int64 ans;
void Solve() {
int i,j,k;
head = tail = 0;
qu[++head] = arr[1];
for (i = 2; i <= n + 1; ++i) {
while (head > 0 && qu[head].val <= arr[i].val) {
ans += i - qu[head].in - 1;
head--;
}
qu[++head] = arr[i];
}
}
int main()
{
int i,j,k;
while (scanf("%d",&n) != EOF) {
for (i = 1; i <= n; ++i)
scanf("%d",&arr[i].val),arr[i].in = i;
arr[n+1].in = n + 1,arr[n+1].val = 2147480000;
ans = 0;
Solve();
printf("%I64d\n",ans);
}
}
本文ZeroClock原创,但可以转载,因为我们是兄弟。