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 hermessy hairstyle, FJ wants to count the number of other cows that can see thetop 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 cowsall facing east (to the right in our diagrams). Therefore, cow i can seethe 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.
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 cowswhose hairstyle is visible from cow i; please compute the sum of c1through 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 ofcow i.
Output
Line 1: A single integer thatis the sum of c1 through cN.
Sample Input
6
10
3
7
4
12
2
Sample Output
5
题目简介:一群牛排队,头向右。问每头牛能看到前面多少头牛的头(即前方连续有多少头牛比自己矮)。然后算出其总数。
方法:双端队列。队列中存储牛的数组下标,将高度按降序排列。当处理的数据比队列末尾下标对应牛的高度大时,在总数上加上队尾计数器的值,用count保存下此时队尾计数器的值,然后删去队尾。同时在删去后的队尾的计数器上加上(count+1)。数据处理完后,从队尾开始进行类似操作。
例如:队列为10,3,此时处理7,3<7,3不能看到任意一头牛即<3,0>,sum+=0,将3删除,同时10的计数器上加1,表示10能看到1头牛(<10,1>),10>7。继续处理后面的数据,此时队列为10,7。处理4,4小于7,继续处理。处理12,12>4,4不能看到任意一头牛,即<4,0>,sum+=0,将4删除,同时在7的计数器上加1,即<7,1>。继续比较,7<12,sum+=1,
10的计数器上加上2,即<10,3>。10<12,sum+=3。10之前没有数据,删去10即可。接下来处理2,2<12,不进行任何操作。然后数据处理完毕。接着从队尾开始,删去2,<2.,0>,sum+=0。然后在12上加1即<12,1>,sum+=1,删去12。队列为空,完毕。
语言能力有限。。。。。。
#include<iostream> #include<deque> using namespace std; struct node { long long int high; int count; }cow[80001]; int main() { int n, i; scanf("%d",&n); for(i = 0;i<n;i++) { scanf("%lld",&cow[i].high); } deque<int> q; q.clear(); long long sum = 0; for(i = 0;i<n;i++) { int count = 0; while(!q.empty()&&cow[i].high>=cow[q.back()].high) { cow[q.back()].count += count; sum += cow[q.back()].count; count = cow[q.back()].count + 1; q.pop_back(); } if(!q.empty()) { cow[q.back()].count += count; } q.push_back(i); } int count = 0; while(!q.empty()) { cow[q.back()].count += count; sum += cow[q.back()].count; count = cow[q.back()].count + 1; q.pop_back(); } printf("%lld\n",sum); system("pause"); return 0; }