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.
题目大意
将一张照片从左到右分为N个垂直部分。照片中的建筑物可以被视为矩形,一栋建筑可以跨越几个连续的部分,但每个部分只能包含一个可见的建筑,或者根本没有建筑(高度为0)。根据每个部分的高度,求出照片中最少建筑物数量。
解题思路
关键:如果这两个矩形之间的建筑物中出现了更低的矩形,那么这两个就一定不能连成一个建筑物,比如高度分别为 2, 1, 2 是有3个建筑的。因此,们需要把不断递增的序列保存下来,然后维护这个序列保持严格递增,即可得到答案,即维护一个单调栈。
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <stack>
using namespace std;
stack<int> s;
int main(){
int n;
int case_cnt=0;
int ans;
while(scanf("%d", &n) != EOF){
ans =0;
int x;
while(n--){
scanf("%d", &x);
if(s.empty()){
s.push(x);
continue;
}
if(x>s.top()){
s.push(x);
}
else if(x < s.top()){
while((!s.empty()) && (s.top()>x)){
ans ++;
s.pop();
}
if(s.empty()){
s.push(x);
continue;
}
if(s.top() != x){
s.push(x);
}
}
}
while(!s.empty()){
if(s.top()!=0){
ans++;
}
s.pop();
}
printf("Case %d: %d\n", ++case_cnt, ans);
}
非单调栈方法的错误原因
一开始没有学习使用单调栈的时候,我只是把高度相同的建筑物去重的,而这并没有考虑2, 1, 2是有三座建筑物的情况。并且不使用单调栈会使用到两层循环,导致time limit。
以下是不能AC 的非单调栈代码,呜呜呜,算是试错啦。
#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
int a[1000005];
int main() {
int n;
int ans;
int case_cnt=0;
while(scanf("%d", &n) != EOF) {
for(int i=0; i<n; i++) {
scanf("%d", &a[i]);
}
ans = n;
if(n==1) {
if(a[0]!=0){
ans = 1;
}
else{
ans = 0;
}
}
else if(n>1) {
if(a[0] == 0){
ans--;
}
for(int j=1; j<n; j++) {
for(int k=0; k<j; k++) {
if((a[k] == a[j]) || (a[j]==0)) {
ans--;
break;
}
}
}
}
printf("Case %d: %d\n", ++case_cnt, ans);
}
return 0;
}