上个月就写了一道题。。。惭愧。
这道题看着像是线段树之类的,想想觉得挺复杂。偷懒看了discuss上面这篇帖子,然后就震惊了:竟然有这么简洁的做法!
http://poj.org/showmessage?message_id=181975
这里面用一个set<int>保存所有被炸毁的村庄。然后如果查询x连接的村庄,只需要知道前后被炸毁的村庄,这两个村庄之前的就是连接的村庄(x在这个区间内)。这里用到了set#lower_bound的方法。c++的set用的是tree,刚好是排序过的。
thestoryofsnow | 2892 | Accepted | 2568K | 391MS | C++ | 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;
}