P2866

[USACO06NOV]Bad Hair Day S

题面翻译

农夫约翰有\(N (N \leq 80000)\)头奶牛正在过乱头发节。每一头牛都站在同一排面朝东方,而且每一头牛的身高为\(h_i\)。第\(N\)头牛在最前面,而第\(1\)头牛在最后面。
对于第\(i\)头牛前面的第\(j\)头牛,如果\(h_i>h_{i+1}\)并且\(h_i>h_{i+2}\) \(\cdots\) \(h_i>h_j\),那么认为第\(i\)头牛可以看到第\(i+1\)到第\(j\)头牛

定义\(C_i\)为第\(i\)头牛所能看到的别的牛的头发的数量。请帮助农夫约翰求出\(\sum_{i=1}^n C_i\)

Consider this example:

        -
-       -
-   -   -
-   -   -
- - - - -
- - - - - -
1 2 3 4 5 6

Cows facing right -->

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.

输入格式

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.

输出格式

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

样例 #1

样例输入 #1

6
10
3
7
4
12
2

样例输出 #1

5
单调栈 但是我的另一种写法为什么不对……
AC
#include<bits/stdc++.h>
using namespace std;
int n,h;
int pt,st[80005];
int main()
{
	ios::sync_with_stdio(false);
	cin>>n;
	long long ans=0;
	for(int i=1;i<=n;i++)
	{
		cin>>h;
		while(pt>0&&st[pt]<=h)pt--;
		ans+=pt;
		st[++pt]=h;
	}
	cout<<ans<<"\n";
	return 0;
}
WA
#include<bits/stdc++.h>
using namespace std;
#define int long long
int n;int a[80005];
int st[80005],pt,ans[80005];
signed main()
{
	ios::sync_with_stdio(false);
	cin>>n;
	for(int i=1;i<=n;i++)cin>>a[i];
	a[0]=LONG_MAX;
//	a[n+1]=INT_MAX;
	for(int i=1;i<=n;i++)
	{
		if(a[i]<=a[st[pt]])
		{
			st[++pt]=i;
		}
		else
		{
			ans[st[pt]]=i;
			pt--;pt++;
			st[pt]=i;
			while(a[st[pt]]>a[st[pt-1]]&&pt>=1)
			{
				ans[st[pt-1]]=st[pt];
				pt--;
				st[pt]=i;
			}
		}
	}
	int tot=0;
//	for(int i=1;i<=n;i++)
//		cout<<ans[i]<<" ";cout<<"\n";
	for(int i=1;i<=n-1;i++)
	{
		if(ans[i]!=0)
		tot+=ans[i]-1-i;
		else tot+=n+1-i-1;
	}
	cout<<tot<<"\n";
	return 0;
}
posted @ 2023-01-15 10:56  PKU_IMCOMING  阅读(12)  评论(0)    收藏  举报