poj2892

树状数组+二分

View Code
#include <iostream>
#include
<cstdlib>
#include
<cstring>
#include
<cstdio>
using namespace std;

#define maxn 50005

int n, m;
char st[5];
int ar[maxn];
bool vis[maxn];
int stk[maxn];
int top;

int lowb(int t)
{
return t &(-t);
}

void add(int i, int v)
{
for (; i < maxn; ar[i] += v, i += lowb(i));
}

int sum(int i)
{
int s = 0;
for (; i > 0; s += ar[i], i -= lowb(i));
return s;
}

int binarysearch(int a)
{
int l = 1;
int r = n + 2;
while (l < r)
{
int mid = (l + r) / 2;
if (sum(mid) >= a)
r
= mid;
else
l
= mid + 1;
}
return l;
}

int main()
{
//freopen("t.txt", "r", stdin);
memset(vis, 0, sizeof(vis));
scanf(
"%d%d", &n, &m);
add(
1, 1);
while (m--)
{
int a;
scanf(
"%s", st);
if (st[0] == 'D')
{
scanf(
"%d", &a);
a
++;
stk[top
++] = a;
vis[a]
= true;
add(a,
1);
}
else if (st[0] == 'R')
{
a
= stk[--top];
vis[a]
= false;
add(a,
-1);
}
else
{
scanf(
"%d", &a);
a
++;
if (vis[a])
{
printf(
"0\n");
continue;
}
a
= sum(a);
int s = binarysearch(a);
int e = binarysearch(a + 1);
printf(
"%d\n", e - s - 1);
}
}
return 0;
}
posted @ 2011-09-13 19:05  金海峰  阅读(340)  评论(0编辑  收藏  举报