Bad Hair Day(单调栈)
题目描述:
Some of Farmer John's N cows (1 ≤ N ≤ 80,0001≤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_i ≤ 1,000,000,0001≤hi≤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.
=
= =
= - = 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.
Example:
input:
6
10
3
7
4
12
2
output:
5
思路:利用单调栈(栈中元素从栈顶往下越来越大)的思想,可以计算出,每只奶牛能被他前面的多少只奶牛看到自己的发型,就反向得到了奶牛看到的发型总和
借用别人的解释:首先弹出元素是因为它右边相邻牛比它高(看不到它的头发并且挡住了该牛的视线),“挡住”这个关键字很重要,这就是说该牛已经看不到后面的其他牛的头发啦,而思路一是按顺序比较身高,统计每头牛前面能看到它头发的牛数,既然该牛望不到后面,那么把它出栈对整个结果没有影响。
例如:10 3 7 4 12 2
②3<10,不弹出,num=0+1(当前栈中元素数),3入栈后 Height_List:10 3
③7 > 3(3 弹出) 7<10(10保留),栈中剩 10 ,num=1+1,7入栈后 Height_List:10 7
④4 < 7,没有弹出,栈中10 7都能看到4,num=2+2 ,4入栈后 Height_List:10 7 4
⑤12大于栈中全部元素,表示栈中所有元素看不到12,全部出栈,num不变,12入栈后 Height_List:12
⑥2 < 12,没有弹出,12能看到2,num=4+1
最后结果num=5
#include<bits/stdc++.h> #include<iostream> #include<cctype> #include<cstdio> #include<cstring> #include<cmath> #include<algorithm> #include<queue> #include<stack> using namespace std; typedef unsigned long long ull; typedef long long ll; typedef pair<ll,ll> pi; #define IOS std::ios::sync_with_stdio(false) #define ls p<<1 #define rs p<<1|1 #define mod 1000000000 + 7 #define PI acos(-1.0) #define INF 1e9 #define N 200000 + 5 /*********************Code*********************/ int n,a[N],ans; stack<int>st; int main(void){ IOS; cin>>n; for(int i = 0;i <n;i++) //如果向左看,逆序输入 cin>>a[i]; for(int i = 0;i < n;i++){ while(!st.empty()&&st.top()<=a[i]) st.pop(); ans +=st.size(); st.push(a[i]); } cout<<ans<<endl; return 0; }

浙公网安备 33010602011771号