BZOJ 1628: [Usaco2007 Demo]City skyline (单调栈)

1628: [Usaco2007 Demo]City skyline

Time Limit: 5 Sec  Memory Limit: 64 MB Submit: 396  Solved: 317 [Submit][Status][Discuss]

Description

Input

第一行给出N,W

第二行到第N+1行:每行给出二个整数x,y,输入的x严格递增,并且第一个x总是1

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

Sample Output

6

思路:我是正着做的,判断条件没有问题,但是细节不好处理,一直WA..大概是有什么地方没想到? 正解是单调栈。

转载一段题解:

答案的上限 肯定是 n, 何时会减一呢? 当有两座楼高度相等且它们的中间没有比它们低的楼。

所以要维护的是一个单调递增的序列, 每次弹出比它大的直到遇到一个和它相等的, 没有相等的话就把 它加入这个序列中。

实现很简单。

 1/* ***********************************************
 2Author :111qqz
 3Created Time :2016年04月04日 星期一 15时23分45秒
 4File Name :code/bzoj/1628.cpp
 5************************************************ */
 6
 7#include <cstdio>
 8#include <cstring>
 9#include <iostream>
10#include <algorithm>
11#include <vector>
12#include <queue>
13#include <set>
14#include <map>
15#include <string>
16#include <cmath>
17#include <cstdlib>
18#include <ctime>
19#define fst first
20#define sec second
21#define lson l,m,rt<<1
22#define rson m+1,r,rt<<1|1
23#define ms(a,x) memset(a,x,sizeof(a))
24typedef long long LL;
25#define pi pair < int ,int >
26#define MP make_pair
27
28using namespace std;
29const double eps = 1E-8;
30const int dx4[4]={1,0,0,-1};
31const int dy4[4]={0,-1,1,0};
32const int inf = 0x3f3f3f3f;
33const int N=1E6+7;
34int n,w;
35int x[N],y[N];
36int st[N];
37int main()
38{
39	#ifndef  ONLINE_JUDGE 
40	freopen("code/in.txt","r",stdin);
41  #endif
42
43	ios::sync_with_stdio(false);
44	cin>>n>>w;
45	for ( int i = 1 ; i <= n ; i++)
46	{
47	    cin>>x[i]>>y[i];
48	}
49
50	int top = 0;
51	int ans = n;
52	for ( int i = 1 ;i  <= n ; i++)
53	{
54	    while (top&&y[i]<st[top]) top--;
55	    if (st[top]==y[i]) ans--;
56	    else st[++top] = y[i];
57	}
58	cout<<ans<<endl;
59
60
61
62  #ifndef ONLINE_JUDGE  
63  fclose(stdin);
64  #endif
65    return 0;
66}