跳到正文

题解

P16395 [ECUSTPC 2026 Spring] 星之所在 题解

幸存者约 5 分钟
原文
文章信息与版本

文章信息

收录
2026年5月2日
更新
2026年5月2日
篇幅
约 5 分钟
题目
P16395

版本

  1. v1当前

为啥题解区的做法都这么难写啊,又是主席树又是点分治又是树上莫队的,这里有一个十分钟写完且跑得比单 log⁡\log 快的根号做法。

当 ∣S∣k+1≥B\frac{|S|}{k}+1\ge B 时,可能成为答案的数不会超过 nB\frac{n}{B} 个,O(n2B)O(\frac{n^2}{B}) 预处理每个点到根的路径上每种数的出现次数后即可 O(1)O(1) 判断一个数出现次数是否大于 ∣S∣k\frac{|S|}{k},这部分时间复杂度不超过 O(n2B+qB)O(\frac{n^2}{B}+qB)。

否则,直接暴力取出整条路径,求出答案,这部分时间复杂度不超过 O(∑kB)O(\sum kB)。

视 n,q,∑kn,q,\sum k 同阶,取 B=O(n)B=O(\sqrt{n}) 即可,总时间复杂度 O(n)O(\sqrt{n})。

核心部分代码:

C++
vi vec, v[100010];
int a[100010], c[100010], cnt[100010], dep[100010], f[100010][20];
int s[100010][510];
void dfs(int x, int fa)
{
	dep[x] = dep[fa] + 1, f[x][0] = fa;
	for (int i = 1; i <= 19; i++) f[x][i] = f[f[x][i - 1]][i - 1];
	for (int i = 0; i < vec.size(); i++) s[x][i] = s[fa][i] + (a[x] == vec[i]);
	for (auto i : v[x])
	{
		if (i == fa) continue;
		dfs(i, x);
	}
}
int lca(int x, int y)
{
	if (dep[x] < dep[y]) swap(x, y);
	while (dep[x] > dep[y]) x = f[x][__lg(dep[x] - dep[y])];
	if (x == y) return x;
	for (int i = __lg(dep[x]); i >= 0; i--) if (f[x][i] != f[y][i]) x = f[x][i], y = f[y][i];
	return f[x][0];
}
signed main()
{
	ios::sync_with_stdio(0);
	cin.tie(0), cout.tie(0);
	int T;
	cin >> T;
	while (T--)
	{
		int n, q;
		cin >> n >> q;
		for (int i = 1; i <= n; i++)
		{
			v[i].clear();
			c[i] = 0;
		}
		for (int i = 1; i <= n; i++)
		{
			cin >> a[i];
			c[a[i]]++;
		}
		int B = 200;
		vec.clear();
		for (int i = 1; i <= n; i++) if (c[i] >= B) vec.pb(i);
		for (int i = 1; i < n; i++)
		{
			int x, y;
			cin >> x >> y;
			v[x].pb(y), v[y].pb(x);
		}
		dfs(1, 0);
		while (q--)
		{
			int x, y, k;
			cin >> x >> y >> k;
			int p = lca(x, y), len = dep[x] + dep[y] - 2 * dep[p] + 1;
			int t = len / k + 1;
			if (t >= B)
			{
				bool ok = false;
				for (int i = 0; i < vec.size(); i++) if (s[x][i] + s[y][i] - 2 * s[p][i] + (a[p] == vec[i]) >= t)
				{
					ok = true;
					cout << vec[i] << " ";
				}
				if (!ok) cout << -1 << '\n';
				else cout << '\n';
			}
			else
			{
				vi V;
				while (x != p)
				{
					V.pb(x);
					x = f[x][0];
				}
				while (y != p)
				{
					V.pb(y);
					y = f[y][0];
				}
				V.pb(p);
				vi ans;
				for (auto i : V) if (++cnt[a[i]] == t) ans.pb(a[i]);
				sort(ans.begin(), ans.end());
				if (ans.empty()) cout << -1 << '\n';
				else
				{
					for (auto i : ans) cout << i << " ";
					cout << '\n';
				}
				for (auto i : V) cnt[a[i]]--;
			}
		}
	}
	return 0;
}
原文