CF1009F Dominant Indices

题意

给定一棵树,求每一棵子树内距离跟最小的节点数最多的深度。

\(n \le 1e6\)

Sol

dsu 板子。

我们先考虑那个 \(n ^ 2\) 的 dp。

对于每一个节点 \(x\),用 \(f_i\) 表示当前在 \(x\) 子树内深度为 \(i\) 的节点有多少个。

求最大值用一个变量 \(tot\) 表示即可。

考虑直接上启发式合并即可。

Code

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <array>
#include <queue>
using namespace std;
#ifdef ONLINE_JUDGE

#define getchar() (p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, 1 << 21, stdin), p1 == p2) ? EOF : *p1++)
char buf[1 << 23], *p1 = buf, *p2 = buf, ubuf[1 << 23], *u = ubuf;

#endif
int read() {
	int p = 0, flg = 1;
	char c = getchar();
	while (c < '0' || c > '9') {
		if (c == '-') flg = -1;
		c = getchar();
	}
	while (c >= '0' && c <= '9') {
		p = p * 10 + c - '0';
		c = getchar();
	}
	return p * flg;
}
void write(int x) {
	if (x < 0) {
		x = -x;
		putchar('-');
	}
	if (x > 9) {
		write(x / 10);
	}
	putchar(x % 10 + '0');
}
const int N = 1e6 + 5, M = 2e6 + 5;

namespace G {

array <int, N> fir;
array <int, M> nex, to;
int cnt;
void add(int x, int y) {
	cnt++;
	nex[cnt] = fir[x];
	to[cnt] = y;
	fir[x] = cnt;
}

}

array <int, N> ans;

namespace Hpt {

using G::fir; using G::nex; using G::to;

array <int, N> son, fa, dep, siz;
array <int, N> dfn, idx;
int cnt;

void dfs1(int x) {
	cnt++;
	dfn[x] = cnt;
	idx[cnt] = x;
	siz[x] = 1;
	for (int i = fir[x]; i; i = nex[i]) {
		if (to[i] == fa[x]) continue;
		fa[to[i]] = x;
		dep[to[i]] = dep[x] + 1;
		dfs1(to[i]);
		siz[x] += siz[to[i]];
		if (siz[to[i]] > siz[son[x]]) son[x] = to[i];
	}
}

queue <int> q;
array <int, N> cur;
int tot;

void add(int x) {
	q.push(x);
	cur[x]++;
	if (cur[x] > cur[tot]) tot = x;
	else if (cur[x] == cur[tot]) tot = min(tot, x);
}

void clear() {
	while (!q.empty())
		cur[q.front()] = 0, q.pop();
	/* tot = 1e6 + 1; */
}

void dfs2(int x) {
	for (int i = fir[x]; i; i = nex[i]) {
		if (to[i] == fa[x] || to[i] == son[x]) continue;
		dfs2(to[i]); clear();
	}
	tot = dep[x];
	if (son[x]) dfs2(son[x]);
	for (int i = fir[x]; i; i = nex[i]) {
		if (to[i] == fa[x] || to[i] == son[x]) continue;
		for (int j = dfn[to[i]]; j <= dfn[to[i]] + siz[to[i]] - 1; j++)
			add(dep[idx[j]]);
	}
	add(dep[x]);
	ans[x] = tot - dep[x];
}

}

int main() {
	int n = read();
	for (int i = 2; i <= n; i++) {
		int x = read(), y = read();
		G::add(x, y), G::add(y, x);
	}
	/* Hpt::tot = 1e6 + 1; */
	Hpt::dfs1(1), Hpt::dfs2(1);
	for (int i = 1; i <= n; i++)
		write(ans[i]), puts("");
	return 0;
}
posted @ 2023-11-28 15:13  cxqghzj  阅读(1)  评论(0编辑  收藏  举报