NYOJ练习题 how many hairstyles can they see?
how many hairstyles can they see?
時間限制:1000?ms ?|? 內存限制:65535?KB 描述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). 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.
For example:
There are six cows, heights are 10 ?2 ?7 ?3 ?12 ?2.
Now 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!
Lines 2..N+1: Line i+1 contains a single integer that is the height of cow i.
題意:有n頭牛面向右排隊,每頭牛只能看到右邊比它矮的牛,右邊比它高的牛會擋住視線;如果比它高的牛的右邊還有比它矮的牛,它同樣看不到那些牛。求這n頭牛能看到的其他牛的數量的總和。
解法:使用棧。如果棧頂的數大于當前元素,說明棧頂的牛可以看見當前的牛,則把當前的元素壓入棧中;否則,說明棧頂這頭牛看不到當前位置之后的牛了,就可以計算出棧頂的牛可以看到的牛的個數,并讓棧頂元素出棧,然后繼續比較棧頂元素,直到棧頂元素大于當前位置,把當前元素壓入棧中。
#include<cstdio> #include<cstring> #include<algorithm> using namespace std; const int N = 8e4 + 10; int sta[N], pos[N]; int main() {int n, i, a;while(~scanf("%d",&n)){int top = 0;scanf("%d",&a);sta[++top] = a;pos[top] = 1;int ans = 0;for(i = 2; i <= n; i++){scanf("%d",&a);while(top > 0 && sta[top] <= a){ans += i - pos[top] - 1; //求出的ans是top位置的牛能看到的牛的數量top--;}sta[++top] = a;pos[top] = i;}top--; //最后一頭牛一頭也看不到while(top > 0){ans += n - pos[top];top--;}printf("%d\n",ans);}return 0; } /*當找到一個比棧頂元素大的數時,就讓棧頂元素出棧,直到棧空,把當前元素壓入棧中*/總結
以上是生活随笔為你收集整理的NYOJ练习题 how many hairstyles can they see?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: IDEA优雅整合Maven+SSM框架(
- 下一篇: 大厂十年:我的三段职业经历和八条建议!