#include<queue>#include<cstdio>#include<cstring>#include<iostream>usingnamespace std;
constint N = 7e4 + 100;
int n, sz[N], root, max_root, du[N], g[N], dis[N], ans[N];
vector <int> G[N];
bool in[N];
structSZSJ {
int f[N << 1], n;
voidclear(int m){
n = m; for (int i = 1; i <= n; i++) f[i] = 0;
}
voidadd(int x, int y){
for (; x <= n; x += x & (-x))
f[x] += y;
}
intquery(int x){
int re = 0;
for (; x; x -= x & (-x))
re += f[x];
return re;
}
}T;
voidInit(){
queue <int> q;
for (int i = 1; i <= n; i++) if (du[i] == 1) q.push(i), in[i] = 1;
while (!q.empty()) {
int now = q.front(); q.pop();
for (int i = 0; i < G[now].size(); i++) { int x = G[now][i];
if (in[x]) continue;
g[x] = g[now] + 1; in[x] = 1; q.push(x);
}
}
memset(in, 0, sizeof(in));
dis[0] = -1;
}
voiddfs0(int now, int father){
sz[now] = 1; dis[now] = dis[father] + 1;
for (int i = 0; i < G[now].size(); i++) { int x = G[now][i];
if (x == father || in[x]) continue;
dfs0(x, now); sz[now] += sz[x];
}
}
voidget_root(int now, int father, int sum){
int maxn = sum - sz[now];
for (int i = 0; i < G[now].size(); i++) { int x = G[now][i];
if (x == father || in[x]) continue;
get_root(x, now, sum);
maxn = max(maxn, sz[x]);
}
if (maxn < max_root) max_root = maxn, root = now;
}
int dadi;
voiddfs1(int now, int father){
ans[now] += T.query(dis[now] + dadi);
for (int i = 0; i < G[now].size(); i++) { int x = G[now][i];
if (x == father || in[x]) continue;
dfs1(x, now);
}
}
voiddfs2(int now, int father){
T.add(g[now] - dis[now] + dadi, 2 - du[now]);//加sz[now]防止负号 for (int i = 0; i < G[now].size(); i++) { int x = G[now][i];
if (x == father || in[x]) continue;
dfs2(x, now);
}
}
voidclac(int now){
dadi = sz[now];
T.clear(sz[now] * 2);
for (int i = 0; i < G[now].size(); i++) { int x = G[now][i];
if (in[x]) continue;
dfs1(x, now);
dfs2(x, now);
}
T.clear(sz[now] * 2);
T.add(g[now] + dadi, 2 - du[now]);
for (int i = G[now].size() - 1; i >= 0; i--) { int x = G[now][i];
if (in[x]) continue;
dfs1(x, now);
dfs2(x, now);
}
ans[now] += T.query(dadi);
}
voidwork(int now){
in[now] = 1;
dfs0(now, 0);
clac(now);
for (int i = 0; i < G[now].size(); i++) { int x = G[now][i];
if (in[x]) continue;
max_root = 2e9; get_root(x, now, sz[x]);
work(root);
}
}
intmain(){
scanf("%d", &n);
for (int i = 1; i < n; i++) {
int x, y; scanf("%d %d", &x, &y);
G[x].push_back(y); G[y].push_back(x);
du[x]++; du[y]++;
}
Init();
dfs0(1, 0);
max_root = 2e9; get_root(1, 0, n);
work(root);
for (int i = 1; i <= n; i++)
if (du[i] != 1) printf("%d\n", ans[i]);
elseprintf("1\n");
return0;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现