杭电OJ第4252题 A Famous City(题目链接)。
A Famous City
Problem 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
3
1 2 3
3
1 2 1Sample Output
Case 1: 3
Case 2: 2Hint
The possible configurations of the samples are illustrated below:
Source
题目大意:房子有高有矮。测量每一片区间能看到最高的房子高度,作为输入。输出这片区间至少有几栋房子。例如上图右边,输入的是1 2 1,左右两个1可能是同一栋房子,中间被高度2的那一栋房子遮住。
解题思路:建立一个栈。从左往右依次读取数据。如果栈空,则入栈。注意:0不要入栈。否则,判断栈顶高度是否大于当前高度,如果大于,则循环出栈(同时栋数自增一),直到栈顶高度不大于当前高度为止。然后,如果栈空,则除了0以外,其它数字都入栈。在栈不空的情况下,如果栈顶高度等于当前高度,则继续下一轮循环。如果在栈不空的情况下,栈顶高度小于当前高度,当前高度入栈。全部数据录入完毕后,循环出栈(并让栋数自增一),直到栈空为止。
C++语言源代码:
#include <cstdio> #include <cstdlib> #include <cassert> #include <stack> using namespace std; int main (void) { int i, n, h, count, cas = 0; while ( scanf( "%d", &n ) != EOF ) { cas ++; stack<int>S; count = 0; for ( i = 0; i < n ; i ++ ) { scanf( "%d", &h ); while ( (!S.empty()) && (S.top()>h) ) { count ++; S.pop(); } if ( S.empty() ) { if ( h != 0 ) S.push(h); } else { if ( S.top() == h ) continue; else if ( S.top() < h ) S.push(h); else // S.top() > h assert(false); } } while ( !S.empty() ) { count ++; S.pop(); } printf( "Case %d: %d\n", cas, count ); } return EXIT_SUCCESS; }