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, 何时会减一呢? 当有两座楼高度相等且它们的中间没有比它们低的楼。

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

实现很简单。

/* ***********************************************
Author :111qqz
Created Time :2016年04月04日 星期一 15时23分45秒
File Name :code/bzoj/1628.cpp
************************************************ */
 1#include <cstdio>
 2#include <cstring>
 3#include <iostream>
 4#include <algorithm>
 5#include <vector>
 6#include <queue>
 7#include <set>
 8#include <map>
 9#include <string>
10#include <cmath>
11#include <cstdlib>
12#include <ctime>
13#define fst first
14#define sec second
15#define lson l,m,rt<<1
16#define rson m+1,r,rt<<1|1
17#define ms(a,x) memset(a,x,sizeof(a))
18typedef long long LL;
19#define pi pair < int ,int >
20#define MP make_pair
 1using namespace std;
 2const double eps = 1E-8;
 3const int dx4[4]={1,0,0,-1};
 4const int dy4[4]={0,-1,1,0};
 5const int inf = 0x3f3f3f3f;
 6const int N=1E6+7;
 7int n,w;
 8int x[N],y[N];
 9int st[N];
10int main()
11{
12	#ifndef  ONLINE_JUDGE 
13	freopen("code/in.txt","r",stdin);
14  #endif
1	ios::sync_with_stdio(false);
2	cin>>n>>w;
3	for ( int i = 1 ; i <= n ; i++)
4	{
5	    cin>>x[i]>>y[i];
6	}
1	int top = 0;
2	int ans = n;
3	for ( int i = 1 ;i  <= n ; i++)
4	{
5	    while (top&&y[i]<st[top]) top--;
6	    if (st[top]==y[i]) ans--;
7	    else st[++top] = y[i];
8	}
9	cout<<ans<<endl;
1  #ifndef ONLINE_JUDGE  
2  fclose(stdin);
3  #endif
4    return 0;
5}