POJ 3250(单调栈)

                                        Bad Hair Day
Time Limit: 2000MS   Memory Limit: 65536K
Total Submissions: 26390   Accepted: 9037

Description

Some of Farmer John's N cows (1 ≤ N ≤ 80,000) are having a bad hair day! Since each cow is self-conscious about her messy hairstyle, FJ wants to count the number of other cows that can see the top of other cows' heads.

Each cow i has a specified height hi (1 ≤ h≤ 1,000,000,000) and is standing in a line of cows all facing east (to the right in our diagrams). Therefore, cow i can see the tops of the heads of cows in front of her (namely cows i+1, i+2, and so on), for as long as these cows are strictly shorter than cow i.

Consider this example:

        =
=       =
=   -   =         Cows facing right -->
=   =   =
= - = = =
= = = = = =
1 2 3 4 5 6

Cow#1 can see the hairstyle of cows #2, 3, 4
Cow#2 can see no cow's hairstyle
Cow#3 can see the hairstyle of cow #4
Cow#4 can see no cow's hairstyle
Cow#5 can see the hairstyle of cow 6
Cow#6 can see no cows at all!

Let ci denote the number of cows whose hairstyle is visible from cow i; please compute the sum of c1 through cN.For this example, the desired is answer 3 + 0 + 1 + 0 + 1 + 0 = 5.

Input

Line 1: The number of cows, N.
Lines 2..N+1: Line i+1 contains a single integer that is the height of cow i.

Output

Line 1: A single integer that is the sum of c1 through cN.

Sample Input

6
10
3
7
4
12
2

Sample Output

5


题意:n头牛,每头牛有一个高度,每头牛都往右面看,问每头牛能看到后脑勺的个数和是多少。规定一头牛可以看到后面比自己矮的牛的后脑勺(挡住了就看不到了)。

思路:单调栈跑一遍,如果当前 i 的高度低于栈顶的牛 x 的高度,则ans += tail (tail为栈中的个数),如果当前 i 的高度高于等于栈顶的牛 x 的高度,则出栈。   i 入栈

  输出ans即可。

 

#include <iostream>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <string>
#include <map>
#include <iomanip>
#include <algorithm>
#include <queue>
#include <stack>
#include <set>
#include <vector>
//const int maxn = 1e5+5;
#define ll long long
#define inf  0x3f3f3f3f
#define FOR(i,a,b) for( int i = a;i <= b;++i)
#define bug cout<<"--------------"<<endl

ll gcd(ll a,ll b){return b?gcd(b,a%b):a;}
ll lcm(ll a,ll b){return a/gcd(a,b)*b;}
const int maxn = 80100;
using namespace std;
int n;
ll a[maxn];
int que[maxn];
ll sum[maxn];
int main()
{
    scanf("%d",&n);
    for(int i = 1;i <= n; ++i)
    {
        scanf("%I64d",a+i);
    }
    //stack<int>sta;
    int tail = 0;
    ll ans = 0;
    for(int i = 1;i <= n; ++i)
    {
        if(tail == 0) {que[++tail] = i; continue;}
        while(a[i] >= a[que[tail]] && tail > 0 ) tail--;
        //for(int j = 1 ; j <= tail ; ++j) sum[que[j]]++;
        ans += tail;
        que[++tail] = i;
    }
    //for(int i = 1;i <= n; ++i) ans += sum[i];

    printf("%I64d\n",ans);
}

 

 

posted @ 2019-10-14 18:33  阿斯水生产线  阅读(175)  评论(0编辑  收藏  举报