UVAlive 7487 Association of Cats and Magical Lights(线段树)

给定一棵树,每个节点上有一个灯泡  灯泡颜色不同,对于每次询问输出任意节点的子树中的数目为奇数的灯泡数目

#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <string.h>
#include <algorithm>
#include <cmath>
#include <stack>
#include <queue>
#include <set>
#include <vector>
#include <bitset>
using namespace std;

typedef long long ll;

typedef pair<int, int> pii;

bitset<101> tr[(300000 + 10) << 2];
struct node
{
	int color;
	int l, r;
	vector<int>child;
	int cot;
};
node tree[300000 + 10];
int in[300000 + 10];
int fa[300000 + 10];

void updata(int l, int r, int now, int tar, int col)
{
	if (l == r&&l == tar)
	{
		tr[now].reset();
		tr[now][col] = 1;
	}
	else
	{
		int mid = (l + r) >> 1;
		if (tar <= mid)updata(l, mid, now << 1, tar, col);
		else updata(mid + 1, r, now << 1 | 1, tar, col);
		tr[now] = tr[now << 1] ^ tr[now << 1 | 1];
	}
}

bitset<101> query(int l, int r, int now, int ql, int qr)
{
	if (l == ql&&r == qr)return tr[now];
	else
	{
		int mid = (l + r) >> 1;
		if (qr <= mid)return query(l, mid, now << 1, ql, qr);
		else if (ql>mid)return query(mid + 1, r, now << 1 | 1, ql, qr);
		else return query(l, mid, now << 1, ql, mid) ^ query(mid + 1, r, now << 1 | 1, mid + 1, qr);
	}
}


void init()
{
	for (int i = 0; i<300000 + 10; i++)
	{
		tree[i].l = tree[i].r = 0;
		tree[i].cot = 1;
		tree[i].child.clear();
		in[i] = 0;
	}
	for (int i = 0; i<((300000 + 10) << 2); i++)tr[i].reset();
}


int main()
{
	int n, m;
	while (cin >> n >> m)
	{
		init();
		for (int i = 1; i <= n; i++)
			scanf("%d", &tree[i].color);
		for (int i = 2; i <= n; i++)
		{
			int nxt;
			scanf("%d", &fa[i]);
			tree[fa[i]].child.push_back(i);
			in[fa[i]]++;
		}
		queue<int>q;
		for (int i = 1; i <= n; i++)
		{
			if (in[i] == 0)q.push(i);
		}
		while (!q.empty())
		{
			int t = q.front();
			q.pop();
			tree[fa[t]].cot += tree[t].cot;
			in[fa[t]]--;
			if (!in[fa[t]])q.push(fa[t]);
		}
		q.push(1);
		tree[1].l = 1;
		while (!q.empty())
		{
			int t = q.front();
			q.pop();
			tree[t].r = tree[t].l + tree[t].cot - 1;
			int pp = tree[t].l + 1;
			for (int i = 0; i<tree[t].child.size(); i++)
			{
				int ccc = tree[t].child[i];
				tree[ccc].l = pp;
				pp += tree[ccc].cot;
				q.push(ccc);
			}
		}
		for (int i = 1; i <= n; i++)
		{
			updata(1, n, 1, tree[i].l, tree[i].color);
		}
		while (m--)
		{
			int x, y;
			scanf("%d%d", &x, &y);
			if (x == 0)
			{
				bitset<101> kk = query(1, n, 1, tree[y].l, tree[y].r);
				printf("%d\n", kk.count());
			}
			else
			{
				updata(1, n, 1,tree[y].l,x );
			}
		}
	}
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值