POJ 2892解题报告

上个月就写了一道题。。。惭愧。

这道题看着像是线段树之类的,想想觉得挺复杂。偷懒看了discuss上面这篇帖子,然后就震惊了:竟然有这么简洁的做法!

http://poj.org/showmessage?message_id=181975

这里面用一个set<int>保存所有被炸毁的村庄。然后如果查询x连接的村庄,只需要知道前后被炸毁的村庄,这两个村庄之前的就是连接的村庄(x在这个区间内)。这里用到了set#lower_bound的方法。c++的set用的是tree,刚好是排序过的。

thestoryofsnow2892Accepted2568K391MSC++1224B
/* 
ID: thestor1 
LANG: C++ 
TASK: poj2892 
*/
#include <iostream>
#include <fstream>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <limits>
#include <string>
#include <vector>
#include <list>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <algorithm>
#include <cassert>

using namespace std;

int main()
{
	stack<int> st;
	set<int> destroyeds;

	int n, m;
	scanf("%d%d", &n, &m);

	// set a left bound "0"
	destroyeds.insert(0);
	// set a right bound "n + 1"
	destroyeds.insert(n + 1);

	char type;
	int x;
	for (int i = 0; i < m; ++i)
	{
		scanf(" %c", &type);
		// D x: The x-th village was destroyed.
		if (type == 'D')
		{
			scanf("%d", &x);
			st.push(x);
			destroyeds.insert(x);
		}
		else if (type == 'Q')
		{
			scanf("%d", &x);
			// the next village that is no less than x
			set<int>::iterator iter = destroyeds.lower_bound(x);
			int nextvillage = *iter;
			// if x is destroyed, return 0
			if (nextvillage == x)
			{
				printf("0\n");
			}
			else
			{
				int previousvillage = *(--iter);
				printf("%d\n", nextvillage - previousvillage - 1);
			}
		}
		else
		{
			assert(type == 'R');
			x = st.top();
			st.pop();
			destroyeds.erase(x);
		}
	}

	return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值