问题 H: A Famous City
时间限制: 1 S e c 1 Sec 1Sec 内存限制: 128 M B 128 MB 128MB
题目描述
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.
输入
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.
输出
For each test case, display a single line containing the case number and the minimum possible number of buildings in the photo.
样例输入 Copy
3
1 2 3
3
1 2 1
样例输出 Copy
Case 1: 3
Case 2: 2
提示
The possible configurations of the samples are illustrated below:
题目大意:多栋高低不同的高楼被相机拍下,在相片中呈现的状态是排成一列的矩形部分大楼的一部分可能被其他的楼给挡住了,高度相同的高楼可能是同一栋高楼。给出各个高度,求最少的楼的数量。
解题思路:对于当前高度,如果高于左边的高度,则楼的数量必定加一;如果等于左边的高度,显然,和左边的同一高度的楼属于同一栋楼;如果小于左边的高度,该高度的左侧一定不能和右侧的 高度同属一栋楼,因此向左搜寻第一个小于等于当前高度的楼,如果搜到的等于当前高度,总的楼的数量不变,否则加一。特别注意一点就是,高度是0的情况,出现高度为0,则和刚开始的状态一样,清空栈,同样的方法计算即可。
上代码:
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
const int N = 100010;
int st[N];
int main()
{
int k = 1;
int n;
while (cin >> n)
{
memset(st, 0, sizeof st);
int ans = 0, s = 0;
for (int i = 0;i < n;i++)
{
int x;
cin >> x;
if (x == 0)
{
while (s) s--;
continue;
}
while (s && st[s] > x)
{
s--;
}
if (!s || st[s] < x) {
st[++s] = x;
ans++;
}
}
cout << "Case " << k++ << ": " << ans << endl;
}
return 0;
}