LCA板子,TLE辣!
查看原帖
LCA板子,TLE辣!
743373
Vitamin_B楼主2024/9/27 12:45

rt

# include <bits/stdc++.h>

# define I return

# define AK 0

# define IOI ;

using namespace std;

typedef long long ll;

typedef pair <int, int> pii;

int t, n, m, x, y, z, l, f[20][10005], depth[10005], s[10005];

string op;

vector <pii> v[10005];

void dfs (const int x) {

	depth[x] = depth[f[0][x]] + 1;

	for (const pii& i : v[x])
		if (i.first != f[0][x])
			f[0][i.first] = x, s[i.first] = s[x] + i.second, dfs (i.first);

	return ;

}

void init (const int x) {

	dfs (x);

	for (int i = 1; i <= 15; ++ i)
		for (int j = 1; j <= n; ++ j)
			f[i][j] = f[i - 1][f[i - 1][j]];
//	for (int i = 0; i <= 2; ++ i) for (int j = 1; j <= n; ++ j) cerr << j << ',' << i << ':' << f[i][j] << '\n';
	return ;

}

int lca (int x, int y) {
//	cout << x << ',' << y << '\n';
	if (depth[x] < depth[y])
		swap (x, y);
//	cout << x << ',' << y << '\n';
	for (int i = 0, tmp = depth[x] - depth[y]; i <= 15; ++ i)
		if (tmp >> i & 1)
			x = f[i][x];
//	cout << x << ',' << y << '\n';
	if (x == y)
		return x;

	for (int i = 15; ~i; -- i)
		if (f[i][x] != f[i][y])
			x = f[i][x], y = f[i][y];
//	cout << x << ',' << y << '\n';
//	cout << f[0][x] << ',' << f[0][y] << '\n';
	return f[0][x];

}

int find (int x, const int y) {
//	cerr << x << ',' << y << '\n';
	for (int i = 0; i <= 15; ++ i)
		if (y >> i & 1)
			x = f[i][x];

	return x;

}

int main () {

	ios::sync_with_stdio (0);

	cin.tie (0);

	cout.tie (0);

	cin >> t;

	while (t --) {

		cin >> n;

		for (int i = 1; i < n; ++ i)
			cin >> x >> y >> z, v[x].emplace_back (y, z), v[y].emplace_back (x, z);

		init (1);

		while (cin >> op, op[1] != 'O') {

			cin >> x >> y, l = lca (x, y);

			if (op[0] == 'D')
				cout << s[x] + s[y] - 2 * s[l] << '\n';
			else {

				cin >> z;
//			cerr << l << ':' << depth[x] - depth[l] + 1 << ',' << depth[x] + depth[y] - 2 * depth[l] - z + 1 << '\n';
				if (z <= depth[x] - depth[l] + 1)
					cout << find (x, z - 1) << '\n';
				else
					cout << find (y, depth[x] + depth[y] - 2 * depth[l] - z + 1) << '\n';

			}

		}

	}

	I AK IOI

}
/*
6
1 2 1
2 4 1
2 5 2
1 3 1
3 6 2
KTH 4 6 4
DONE
*/
2024/9/27 12:45
加载中...