poj 3250 Bad Hair Day(单调栈)
题意:
n头牛排成一列,第n只牛在最前面,第1只牛在最后面。第i只牛能看到的牛的个数是,它前面的且没有被其他牛遮挡的牛的个数,遮挡的条件是高度大于或者相同。现在问所有牛能看到的牛的个数的和。
思路:单调栈。具体见代码。1A.
/* ***********************************************
Author :111qqz
Created Time :2016年08月03日 星期三 05时12分47秒
File Name :code/poj/3250.cpp
************************************************ */
1#include <cstdio>
2#include <cstring>
3#include <iostream>
4#include <algorithm>
5#include <vector>
6#include <queue>
7#include <stack>
8#include <set>
9#include <map>
10#include <string>
11#include <cmath>
12#include <cstdlib>
13#include <ctime>
14#define fst first
15#define sec second
16#define lson l,m,rt<<1
17#define rson m+1,r,rt<<1|1
18#define ms(a,x) memset(a,x,sizeof(a))
19typedef long long LL;
20#define pi pair < int ,int >
21#define MP make_pair
1using namespace std;
2const double eps = 1E-8;
3const int dx4[4]={1,0,0,-1};
4const int dy4[4]={0,-1,1,0};
5const int inf = 0x3f3f3f3f;
6const int N=8E4+7;
7int a[N];
8int c[N];
9stack<int>stk;
10int n;
11int main()
12{
13 #ifndef ONLINE_JUDGE
14 freopen("code/in.txt","r",stdin);
15 #endif
scanf("%d",&n);
for ( int i = 1 ; i <= n ; i++) scanf("%d",&a[i]);
1 a[n+1] = inf;
2 stk.push(n+1);
3 int x;
4 for ( int i = n ; i >=1 ; i--)
5 {
6 for ( x = stk.top() ; a[x]<a[i] ; x = stk.top()) stk.pop();//找到第一个大于等于a[i]的位置
7 c[i] = x-1; //第一个大于等于a[i]的位置的左边就是i号牛能看到的最远的牛,c[i]-i就是i号牛能看到的牛的个数。
8 stk.push(i);
9 }
10// for ( int i = n; i >= 1 ; i--) cout<<"i:"<<i<<" c[i]:"<<c[i]<<endl;
11 LL ans = 0 ;
12 for ( int i = 1 ; i <= n ; i++) ans = ans + 1LL*(c[i]-i);
13 printf("%lld\n",ans);
1 #ifndef ONLINE_JUDGE
2 fclose(stdin);
3 #endif
4 return 0;
5}