比赛 寒假集训2 评测结果 TTTTTTTTTTTTTTTTTTTT
题目名称 轻重边 最终得分 0
用户昵称 赵飞羽 运行时间 22.016 s
代码语言 C++ 内存使用 9.43 MiB
提交时间 2026-02-25 10:56:08
显示代码纯文本
#include <bits/stdc++.h>
using namespace std;

const int N = 100010, L = 19;
int T, n, m, u, v, op, a, b, fa[N], flag, cnt, l;
int hd[N], ver[N*2], val[N], pre[N*2], idx;
int d[N], _fa[N][20], rt;

void add(int x, int y) {
	ver[++idx] = y;
	pre[idx] = hd[x];
	hd[x] = idx;
}

void bfs() {
	d[rt] = 1;
	queue <int> q;
	q.push(rt);
	while (q.size()) {
		int x = q.front(); q.pop();
		for (int i = hd[x]; i; i = pre[i]) {
			int y = ver[i];
			if (d[y]) continue;
			d[y] = d[x] + 1;
			_fa[y][0] = x;
			for (int j = 1; j <= L; j++) _fa[y][j] = _fa[_fa[y][j-1]][j-1];
			q.push(y);
		}
	}
}

int lca (int x, int y) {
	if (d[x] < d[y]) swap(x, y);
	for (int i = L; i >= 0; i--) if (d[_fa[x][i]] >= d[y]) x = _fa[x][i];
	if (x == y) return x;
	for (int i = L; i >= 0; i--) if (_fa[x][i] != _fa[y][i]) x = _fa[x][i], y = _fa[y][i];
	return _fa[x][0];
}

void update(int f, int x, int t) {
	if (x == t) {
		for (int i = hd[x]; i; i = pre[i]) {
			int y = ver[i];
			if (y == f) val[i] = 1, val[i+1] = 1;
			else val[i] = 0, val[i+1] = 0;
//			printf("last dot is %d, now dot is %d, father dot is %d, turn the %dth line from %d to %d into %d\n", f, x, fa[x], i, x, y, val[i]);
		}
		return;
	}
	for (int i = hd[x]; i; i = pre[i]) {
		int y = ver[i];
		if (y == f || y == fa[x]) val[i] = 1, val[i+1] = 1;
		else val[i] = 0, val[i+1] = 0;
//		printf("last dot is %d, now dot is %d, father dot is %d, turn the %dth line from %d to %d into %d\n", f, x, fa[x], i, x, y, val[i]);
	}
	update(x, fa[x], t);
}

void query(int x, int t) {
	if (x == t) return;
	for (int i = hd[x]; i; i = pre[i]) {
		int y = ver[i];
		if (y == fa[x]) cnt += val[i];
	}
	query(fa[x], t);
}

signed main() {
	freopen("edge.in", "r", stdin);
	freopen("edge.out", "w", stdout);
	ios::sync_with_stdio(0);
	cin.tie(0), cout.tie(0);
	cin >> T;
	while (T--) {
		for (int i = 1; i <= n; i++) hd[i] = 0, fa[i] = 0;
		idx = 0;
		cin >> n >> m;
		for (int i = 1; i < n; i++) {
			cin >> u >> v;
			fa[v] = u;
			add(u, v);
			add(v, u);
		}
		for (int i = 1; i <= n; i++) if (!fa[i]) rt = i;
		bfs();
		for (int i = 1; i <= m; i++) {
			cin >> op >> a >> b;
			flag = 0, cnt = 0, l = lca(a, b);
			if (op == 1) {
//					cerr << "LCA of " << a << " and " << b << " is " << l << "\n";
				update(-1, a, l);
				update(-1, b, l);
//					for (int j = 1; j <= n; j++) {
//						for (int k = hd[j]; k; k = pre[k]) {
//							if (ver[k] == fa[j]) {
//								cerr << ver[k] << " to " << j << " is " << (val[k]? "heavy": "light") << "\n";
//							}
//						}
//					}
			} else {
				query(a, l);
				query(b, l);
				cout << cnt << "\n";
			}
		}
	}
	return 0;
}
/*
1
7 7
1 2
1 3
3 4
3 5
3 6
6 7
1 1 7
1 3 6
2 1 7

*/