NYOJ练习题 how many hairstyles can they see?
how many hairstyles can they see?
時(shí)間限制:1000?ms ?|? 內(nèi)存限制: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頭牛面向右排隊(duì),每頭牛只能看到右邊比它矮的牛,右邊比它高的牛會(huì)擋住視線;如果比它高的牛的右邊還有比它矮的牛,它同樣看不到那些牛。求這n頭牛能看到的其他牛的數(shù)量的總和。
解法:使用棧。如果棧頂?shù)臄?shù)大于當(dāng)前元素,說(shuō)明棧頂?shù)呐?梢钥匆?jiàn)當(dāng)前的牛,則把當(dāng)前的元素壓入棧中;否則,說(shuō)明棧頂這頭牛看不到當(dāng)前位置之后的牛了,就可以計(jì)算出棧頂?shù)呐?梢钥吹降呐5膫€(gè)數(shù),并讓棧頂元素出棧,然后繼續(xù)比較棧頂元素,直到棧頂元素大于當(dāng)前位置,把當(dāng)前元素壓入棧中。
#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位置的牛能看到的牛的數(shù)量top--;}sta[++top] = a;pos[top] = i;}top--; //最后一頭牛一頭也看不到while(top > 0){ans += n - pos[top];top--;}printf("%d\n",ans);}return 0; } /*當(dāng)找到一個(gè)比棧頂元素大的數(shù)時(shí),就讓棧頂元素出棧,直到棧空,把當(dāng)前元素壓入棧中*/總結(jié)
以上是生活随笔為你收集整理的NYOJ练习题 how many hairstyles can they see?的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: IDEA优雅整合Maven+SSM框架(
- 下一篇: 大厂十年:我的三段职业经历和八条建议!