您的位置:首页 > 其它

HDU 5372 - Segment Game(树状数组)

2015-08-13 21:29 281 查看
题目:

http://acm.hdu.edu.cn/showproblem.php?pid=5372

题意:

在水平坐标轴上,0操作表示画线段(b,b+i),1操作表示将线段i删去,输出每次增加的线段包含的线段的数量。

思路:

由于b有10^9,所以需要离散化,将所有的坐标存入num数组中,排序去从。在num数组中二分查找每次询问的左右坐标,得到的下标即为离散后的新坐标。

维护两个树状数组,一个表示左端点,一个表示右端点,每次S【r】- S【l-1】即为区间(l,r)的完整线段数量。

做线段删除操作时,两个树状数组都在左端点位置向上减1 即可。

AC.

 #include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#pragma comment (linker,"/STACK:1024000000,1024000000")

using namespace std;
const int maxn = 4e5+5;
int p[maxn], a[maxn], b[maxn], num[maxn];
int cnt, s[2][maxn];

int bit(int x)
{
return x & (-x);
}
void add(int x, int d, int o)
{
while(x <= cnt) {
s[o][x] += d;
x += bit(x);
}
}
int sum(int x, int o)
{
int ret = 0;
while(x > 0) {
ret += s[o][x];
x -= bit(x);
}
return ret;
}

int main()
{
// freopen("in", "r", stdin);
int n, ca = 0;
while(~scanf("%d", &n)) {
cnt = 0;
int c = 0;
for(int i = 1; i <= n; ++i) {
scanf("%d %d", &p[i], &a[i]);
if(!p[i]) {
b[i] = a[i]+ (++c);
num[cnt++] = a[i];
num[cnt++] = b[i];
}
}

sort(num, num+cnt);
cnt = unique(num, num+cnt) - num;
memset(s, 0, sizeof(s));

int ad = 1;
printf("Case #%d:\n", ++ca);
for(int i = 1; i <= n; ++i) {
if(p[i] == 0) {
int aa = lower_bound(num, num+cnt, a[i]) - num + 1;
int bb = lower_bound(num, num+cnt, b[i]) - num + 1;

printf("%d\n", sum(bb, 1) - sum(aa-1, 0));

a[ad] = aa;
b[ad++] = bb;

add(aa, 1, 0);
add(bb, 1, 1);
}
else {
add(a[a[i]], -1, 0);
add(b[a[i]], -1, 1);
}
}

}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  HDU