1683: [Usaco2005 Nov]City skyline 城市地平线
Time Limit: 5 Sec Memory Limit: 64 MBSubmit: 346 Solved: 294
[ Submit][ Status][ Discuss]
Description
Input
第1行:2个用空格隔开的整数N和W.
第2到N+1行:每行包括2个用空格隔开的整数x,y,其意义如题中所述.输入中的x严格递增,并且第一个z总是x.
Output
输出一个整数,表示城市中最少包含的建筑物数量.
Sample Input
10 26
1 1
2 2
5 1
6 3
8 1
11 0
15 2
17 3
20 2
22 1
INPUT DETAILS:
The case mentioned above
1 1
2 2
5 1
6 3
8 1
11 0
15 2
17 3
20 2
22 1
INPUT DETAILS:
The case mentioned above
Sample Output
6
HINT
Source
简单的单调栈。
用一个栈维护不断上升的高度,如果读入一个高度小于当前栈顶就退栈到当前高度大于或等于栈顶,顺带记录答案
然后插入当前高度
最后要清空一下栈
代码:
#include<cstdio>
using namespace std;
const int maxn = 50010;
int top,w,n,stk[maxn];
int main()
{
scanf("%d%d",&n,&w);
int x,s;
int ans = 0;
for (int i = 1; i <= n; i++)
{
scanf("%d%d",&s,&x);
while (x < stk[top])
{
top--;
ans++;
}
while (x == stk[top] && top > 0) top--;
if (x != 0) stk[++top] = x;
}
while (0 < stk[top])
{
top--;
ans++;
}
printf("%d",ans);
return 0;
}