HDU

来源:互联网 发布:360网络收藏夹网页版 编辑:程序博客网 时间:2024/06/06 01:07

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 1
Sample Output
Case 1: 3
Case 2: 2




Hint
The possible configurations of the samples are illustrated below:


题意:给出n个建筑物的图片,从图片上可以知道建筑物的高度(可以为0),图片从左到右依据实际建筑物存在的顺序,问这些图片至少可以代表多少个建筑物.

分析:先把每张图片上的建筑物当做一个独立的建筑,那么就有n种,但是当h为0的时候,这个建筑物就不存在了,ans就要减1,对于h不为0的建筑物来说,就要一一进行比较了,把第i个建筑一次与i-1,i-2,...,1这些个进行高度上的比较,在能够保证前面没有小于第i个的高度的情况下,如果有某一个j(0<j<i)和i的高度相等,可以将i和j视为同一个建筑,ans--(大前提是i和j之间的建筑物高度都比他两高,这样可以把他们中间的部分遮挡起来),当然遇到了比第i个小的,就不用再比下去了,i一定是独立的一个

总的来说,就是判断每一个建筑物是不是独立的一个,判断的方法就是依次与前i-1个进行比较,如果首先遇到了比它小的,那它一定是独立的一个,如果遇到了比他高的继续比较,如果遇到了高度相等的,可以设为不独立的建筑物.

参考代码:

#include<cstdio>#include<cmath>#include<cstring>#include<algorithm>#include<iostream>using namespace std;const int maxn = 1e5+10;int n;int h[maxn];int main(){int cnt = 1;while( ~scanf("%d",&n)){for( int i = 1; i <= n; i++)scanf("%d",&h[i]);int ans = n;int tmp = 0;for( int i = 1; i <= n; i++){if( h[i] == 0)//该处高度为0{ans--;//一定会少一块建筑tmp = i;//下次进行到tmp+1就好}else//判断当前建筑能否与之前的合并为一个建筑{for( int j = i-1; j > tmp; j--){if( h[i] > h[j])break;if( h[i] == h[j]){ans--;break;}}}}printf("Case %d: %d\n",cnt++,ans);}return 0;}






原创粉丝点击