HDU4252--栈

来源:互联网 发布:北京淘宝大学在哪 编辑:程序博客网 时间:2024/05/13 12:04

Description

After Mr. B arrived in Warsaw, he was shocked by the skyscrapers and took several photos. But now when he looks at these photos, he finds in surprise that he isn't able to point out even the number of buildings in it. So he decides to work it out as follows:
- divide the photo into n vertical pieces from left to right. The buildings in the photo can be treated as rectangles, the lower edge of which is the horizon. One building may span several consecutive pieces, but each piece can only contain one visible building, or no buildings at all.
- measure the height of each building in that piece.
- write a program to calculate the minimum number of buildings.
Mr. B has finished the first two steps, the last comes to you.
 

Input

Each test case starts with a line containing an integer n (1 <= n <= 100,000). Following this is a line containing n integers - the height of building in each piece respectively. Note that zero height means there are no buildings in this piece at all. All the input numbers will be nonnegative and less than 1,000,000,000.
 

Output

For each test case, display a single line containing the case number and the minimum possible number of buildings in the photo.
 

Sample Input

31 2 331 2 1
 

Sample Output

Case 1: 3Case 2: 2

Hint

 
此题的一个思路就是如果一个建筑比前面的建筑高,就入栈,如果遇到比前一个等高的,那等高这些都可以看成一个建筑,如果遇到比前一个矮的,那么从这个矮的前一个起,一直到比这个矮的还矮为止,这一部分是隔离开的,可以出栈累加建筑数
The possible configurations of the samples are illustrated below:
 
#include <iostream>#include <stack>#include <cstdio>using namespace std;int A[100008];int main(){int n,t=0;while(cin>>n){t++;stack <int> q;int sum=0;for(int i=1;i<=n;i++){cin>>A[i];}for(int i=1;i<=n;i++){if(q.empty()){q.push(A[i]);continue;}if(A[i]>q.top()){q.push(A[i]);continue;}if(A[i]<q.top()){while((!q.empty())&&(A[i]<q.top())){sum++;q.pop();}q.push(A[i]);}if(A[i]==q.top()){while((!q.empty())&&(A[i]==q.top())){q.pop();}q.push(A[i]);continue;}}while(!q.empty())//这里是此题的一个坑,因为0是木有建筑的{if(q.top()){sum++;}q.pop();}cout<<"Case "<<t<<": "<<sum<<endl;}return 0;}

 
 
 
 
原创粉丝点击