Bad Hair Day (单调栈)

来源:互联网 发布:c webservice json 编辑:程序博客网 时间:2024/06/03 13:48

Bad Hair Day

Time Limit : 4000/2000ms (Java/Other)   Memory Limit : 131072/65536K (Java/Other)
Total Submission(s) : 50   Accepted Submission(s) : 18
Problem 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 ≤ hi≤ 1,000,000,000) and is standing in a line of cows all facing east (to the right in our diagrams). Therefore, cowi 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 cowi.

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 cowi; please compute the sum ofc1 through cN.For this example, the desired is answer 3 + 0 + 1 + 0 + 1 + 0 = 5.

 

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

Output
Line 1: A single integer that is the sum of <i>c</i><sub>1</sub> through <i>c<sub>N</sub></i>.
 

Sample Input
610374122
 

Sample Output
5
 

Source
PKU

题意:

大体意思就是一串数字,以每一个数为起点,向后找比他小的,问总共有多少。‘

思路:

利用栈的后进的先出的特点进行操作,碰见比它大的就出栈,每次只需加上栈里元素的数量即可。

代码:

#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>#include <cmath>#include <string>#include <map>#include <stack>#include <vector>#include <set>#include <stdio.h>#include <queue>#include <iomanip>#define maxn 100000#define mod 1000000007#define INF 0x3f3f3f3f#define exp 1e-6#define pi acos(-1.0)using namespace std;int main(){    ios::sync_with_stdio(false);    int n,i;    long long a[maxn],sum=0;    stack<long long>q;    cin>>n;   // int head=1,tail=0;    for(i=0;i<n;i++)cin>>a[i];    for(i=0;i<n;i++)    {        while(!q.empty()&&q.top()<=a[i])q.pop(); //关键点        sum+=q.size();   //加上栈里元素的个数        q.push(a[i]);    }    cout<<sum<<endl;    return 0;}

单调队列(思路一样):

#include <iostream>#include <cstdio>#include <cstring>#define MAXN 80050#define LL long longusing namespace std;LL q[MAXN];int main(){    int n;    scanf("%d",&n);    LL a;    LL ans=0;    int rear=-1,front=0;    for(int i=0;i<n;i++){        scanf("%I64d",&a);        while(rear>=front&&q[rear]<=a)rear--;        q[++rear]=a;        ans+=rear;    }    cout<<ans<<endl;    return 0;}