B - Blue

B – Blue
解题者:戴**
知识点:单调栈
Time Limit:2000MS Memory Limit:65536KB 64bit IO Format:%lld & %llu
Submit Status Practice POJ 3250
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 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 in our diagrams). Therefore, cow ican 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.
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 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 c 1 through cN.
Sample Input
6
10
3
7
4
12
2
Sample Output
5

题目大意:
站着一排牛,牛从左往右看能看到比自己身高小的牛的发型,但是如果碰到牛的身高比自己高了,那么到此为止。
可以想象一下,当牛是从右往左看时,只能看到比自己身高大的牛,如果比自己身高小,那么到此为止。
解题思路:
用单调栈,从左往右读,栈内元素从栈底到栈顶是递减的,这样如果遇到元素比栈顶元素大,那么就弹出栈顶元素,计算此时栈内元素的个数。然后让遇到的元素进栈,计算此时栈内元素的个数。最后将所有的个数相加即为所得。
源代码:
1:用栈,效率较低

include

include

using namespace std;

define N 80005

stack s;
int main(){
long long sum=0;
int n;
int temp;
cin>>n;
while(n--){
cin>>temp;
while(!s.empty()&&s.top()<=temp)
s.pop();
sum+= s.size();
s.push(temp);
}
cout< return 0;
}

2、用栈的思想,效率高

include

using namespace std;

define N 80010

int Stack[N];

int main()
{
int top = 0, i, n, p;
long long sum = 0;

cin>>n;


while(n--){
    cin>>p;
    while(top>0 && Stack[top]<=p)
        top--;//退栈
    sum += top;
    Stack[++top] = p;//进栈
}

cout<

}

你可能感兴趣的:(B - Blue)