Question link: http://poj.org/problem? Id = 3250
Train of Thought Analysis:
The question requires the sum of the number of cows that each ox sees, that is, the sum of the number of times each ox sees;
How can we determine the number of times each ox is seen?
For a particular ox, the ox who sees it must be on its left, and its height should be higher than that of the ox, therefore, you only need to calculate the number of cows whose height on the left is greater than that on the left;
Consider building a stack. When a cow enters the stack, the height of the stack is smaller than its height, and the rest is greater than its height, in this case, the length of the computing stack can be seen by the ox.
The Code is as follows:
#include<iostream>#include<stack>using namespace std;int main(){ int n; int ans = 0; unsigned long height; stack<unsigned long>S; scanf( "%d", &n ); scanf( "%d", &height ); S.push( height ); for ( int i = 1; i < n; i++ ) { scanf( "%d", &height ); while ( !S.empty() && S.top() <= height ) S.pop(); ans = ans + S.size(); S.push( height ); } while ( !S.empty() ) S.pop(); printf( "%u\n", ans ); return 0;}
Algorithm complexity: O (N)
Poj 3250 bad hair day