标签:线段树
7 9 D 3 D 6 D 5 Q 4 Q 5 R Q 4 R Q 4
1 0 2 4
/*************************************************************************
> File Name: hdu1540.cpp
> Author: ALex
> Mail: 405045132@qq.com
> Created Time: 2015年01月11日 星期日 12时24分34秒
************************************************************************/
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <vector>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 500010;
stack <int> re;
struct node
{
int l, r;
int l_sum;
int r_sum;
}tree[N << 2];
void pushup (int p)
{
tree[p].l_sum = tree[p << 1].l_sum;
tree[p].r_sum = tree[p << 1 | 1].r_sum;
if (tree[p << 1].l_sum == tree[p << 1].r - tree[p << 1].l + 1)
{
tree[p].l_sum += tree[p << 1 | 1].l_sum;
}
if (tree[p << 1 | 1].r_sum == tree[p << 1 | 1].r - tree[p << 1 | 1].l + 1)
{
tree[p].r_sum += tree[p << 1].r_sum;
}
}
void build (int p, int l, int r)
{
tree[p].l = l;
tree[p].r = r;
tree[p].l_sum = tree[p].r_sum = (r - l + 1);
if (l == r)
{
return;
}
int mid = (l + r) >> 1;
build (p << 1, l, mid);
build (p << 1 | 1, mid + 1, r);
}
void update (int p, int pos, int sta)
{
if (tree[p].l == tree[p].r)
{
tree[p].l_sum = tree[p].r_sum = sta;
return;
}
int mid = (tree[p].l + tree[p].r) >> 1;
if (pos <= mid)
{
update (p << 1, pos, sta);
}
else
{
update (p << 1 | 1, pos, sta);
}
pushup (p);
}
int query (int p, int pos)
{
if (tree[p].l == tree[p].r)
{
if (tree[p].l_sum == 1)
{
return 1;
}
return 0;
}
int mid = (tree[p].l + tree[p].r) >> 1;
if (pos <= mid)
{
if (pos >= mid - tree[p << 1].r_sum + 1)
{
return tree[p << 1].r_sum + tree[p << 1 | 1].l_sum;
}
return query (p << 1, pos);
}
else
{
if (pos <= mid + tree[p << 1 | 1].l_sum)
{
return tree[p << 1 | 1].l_sum + tree[p << 1].r_sum;
}
return query (p << 1 | 1, pos);
}
}
int main()
{
int n, m;
int x;
char op[10];
while (~scanf("%d%d", &n, &m))
{
build (1, 1, n);
while (!re.empty())
{
re.pop();
}
while (m--)
{
scanf("%s", op);
if(op[0] == 'R')
{
if (re.empty())
{
continue;
}
update (1, re.top(), 1);
re.pop();
}
else
{
scanf("%d", &x);
if (op[0] == 'D')
{
update (1, x, 0);
re.push(x);
}
else
{
printf("%d\n", query (1, x));
}
}
}
}
return 0;
}hdu1540 && POJ2892 Tunnel Warfare
标签:线段树
原文地址:http://blog.csdn.net/guard_mine/article/details/42610273