City Skyline Description The best part of the day for Farmer John's cows is when the sun sets. They can see the skyline of the distant city. Bessie wonders how many buildings the city has. Write a program that assists the cows in calculating the minimum number of buildings in the city, given a profile of its skyline.
Input * Line 1: Two space separated integers: N and W Output * Line 1: The minimum number of buildings to create the described skyline. Sample Input
Sample Output
Hint INPUT DETAILS: Source USACO 2005 November Silver |
Time Limit: 1000MS | | Memory Limit: 65536K |
Total Submissions: 3083 | | Accepted: 1412 |
算法分析:
题意:
分析:
题意理解很重要,本题关键在于横着楼的判定,他should后面元素的影响,所以我们需要一个数据结构来保存它,那我们不能让跟它一样高的楼层进来,因为它们是一层楼。我们维护一个递增的单调栈,(进栈元素就是楼层),如果当前栈顶元素大于要入栈的元素,那么此时该栈顶元素位置就确定了(因为比它低的点的正视图,不能再被该栈顶元素覆盖) 否则其坐标不会比其低,然后每pop栈顶元素就增加一个楼。这样也保证了,无法让重复的元素进去,不让重复的多余的楼进来。
代码实现:
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cctype>
#include<cmath>
#include<iostream>
#include<sstream>
#include<iterator>
#include<algorithm>
#include<string>
#include<vector>
#include<set>
#include<map>
#include<stack>
#include<deque>
#include<queue>
#include<list>
using namespace std;
const double eps = 1e-8;
typedef long long LL;
typedef unsigned long long ULL;
const int INF = 0x3f3f3f3f;
const int INT_M_INF = 0x7f7f7f7f;
const LL LL_INF = 0x3f3f3f3f3f3f3f3f;
const LL LL_M_INF = 0x7f7f7f7f7f7f7f7f;
const int dr[] = {0, 0, -1, 1, -1, -1, 1, 1};
const int dc[] = {-1, 1, 0, 0, -1, 1, -1, 1};
const int MOD = 1e9 + 7;
const double pi = acos(-1.0);
const int MAXN=5010;
const int MAXM=100010;
const int M=50010;
int main()
{
int n,m;
while(scanf("%d%d",&m,&n)!=EOF)
{
int h[M];
for(int i=1;i<=m;i++)
{
int a;
scanf("%d%d",&a,&h[i]);
}
stack<int> s;
h[0]=0;
h[m+1]=0;
while(!s.empty())
s.pop();
s.push(0);
int ans=0;
for(int i=1;i<=m+1;i++) //n+1d的目的为就叫栈中元素全出来
{
while(!s.empty()&&h[s.top()]>h[i]) //若栈顶元素大于当前值,楼的位置就确定了
{
s.pop();
ans++;
}
if(h[s.top()]!=h[i]) //放入栈
{
s.push(i);
}
}
cout<<ans<<endl;
}
return 0;
}