跳到正文

题解

P7242 [COCI2019-2020#4] Klasika

SegmentTree_约 5 分钟
原文
文章信息与版本

文章信息

发布
2024年12月5日
收录
2025年12月12日
更新
2026年11月21日
篇幅
约 5 分钟
获赞
2
题目
P7242

版本

  1. v1当前

对于树上路径边权异或和,可以转化为 disx⊕disvdis_x \oplus dis_v,其中 disidis_i 表示 ii 到根的路径上的边权异或和。
于是,Query 操作就变成了 bb 的子树中的点的 disdis 异或上 disadis_a 的最大值。
加上 Add 操作后,因为在序列上用树状数组套01-trie还是很好维护的,所以考虑把树拍到序列上。
那要怎么做呢?可以离线建树搞一个 dfndfn 序,初始时树套树只有一个 dis1dis_1,也就是 00,Add 操作就是在 xx 插入一个 disxdis_x,Query 就是区间内异或最大值。
时间复杂度 O(nlog⁡2nlog⁡2V)O(n \log_2 n \log_2 V)。
code:

C++
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define ull unsigned ll
#define ui unsigned int
#define i128 __int128
#define lid (id << 1)
#define rid (id << 1 | 1)
const int N = 2e5+5;
namespace tianyu{
	int n, q;
	struct Quee{
		string op;
		int x, y;
	}Q[N];
	int root[N];
	int trie[N * 200][2], siz[N * 200], tot;
	int now;
	vector<int> G[N];
	int dis[N];
	int dfn[N], end[N], tt;
	void dfs(int u){
		dfn[u] = ++tt;
		for (int v : G[u]){
			dfs(v);
		}
		end[u] = tt;
	}
	void insert(int p, int x){
		if (!root[p]) root[p] = ++tot;
		int u = root[p];
		for (int i = 30;i >= 0;i--){
			int a = (x >> i) & 1;
			if (!trie[u][a]) trie[u][a] = ++tot;
			u = trie[u][a];
			++siz[u];
		}
	}
	int ql[N], qr[N];
	int query(int x){
		int res = 0;
		for (int i = 30;i >= 0;i--){
			int a = (x >> i) & 1;
			int s = 0;
			for (int i = 1;i <= qr[0];i++) s += siz[trie[qr[i]][!a]];
			for (int i = 1;i <= ql[0];i++) s -= siz[trie[ql[i]][!a]];
			if (s){
				res |= (1 << i);
				a = !a;
			}
			for (int i = 1;i <= qr[0];i++) qr[i] = trie[qr[i]][a];
			for (int i = 1;i <= ql[0];i++) ql[i] = trie[ql[i]][a];
		}
		return res;
	}
	void update(int p){
		for (int i = dfn[p];i <= n;i += i & -i){
			insert(i, dis[p]);
		}
	}
	int query(int l, int r, int x){
		ql[0] = qr[0] = 0;
		--l;
		for (int i = r;i;i -= i & -i){
			qr[++qr[0]] = root[i];
		}
		for (int i = l;i;i -= i & -i){
			ql[++ql[0]] = root[i];	
		}
		return query(x);
	}
	void awa(){
		now = 1;
		n = 1;
		cin >> q;
		for (int i = 1;i <= q;i++){
			cin >> Q[i].op >> Q[i].x >> Q[i].y;
			if (Q[i].op == "Add"){
				++n;
				G[Q[i].x].emplace_back(n);
				dis[n] = dis[Q[i].x] ^ Q[i].y;
			}
		}
		dfs(1);
		update(1);
		for (int i = 1;i <= q;i++){
			if (Q[i].op == "Add"){
				update(++now);
			}
			else{
				int x = Q[i].x, y = Q[i].y;
				cout << query(dfn[y], end[y], dis[x]) << '\n';
				
			}
		}
	}
}
signed main(){
	int T = 1;
	while (T--) tianyu::awa();
	return 0;
}
原文