思路
使用两个 。
第一个 对这棵树进行红蓝染色,默认从根节点(节点1)开始进行染色,相邻的节点染上不同的颜色。
原因如下图:
(字难看见谅)
发现相邻的两个节点答案加起来刚好是这个树所有节点的个数。 因此,第二个 的作用,是寻找任意一个被染成蓝色的节点开始寻找可以结束漫步的节点,和任意一个被染成红色的节点开始寻找可以结束漫步的节点。最后统计答案。
设蓝色节点可以结束漫步的节点数有 个则其他蓝色节点可以结束漫步的节点个数有 个。其他红色节点可以结束漫步的节点个数为 个(n为节点的总个数)
最后,输出答案即可。
附上丑陋的代码:
#include <bits/stdc++.h>
#define LL long long
#define for_(i, a, b) for (int i = (a); i <= (b); i++)
#define _for(i, a, b) for (int i = (a); i >= (b); i--)
#define read() freopen("a.in", "r", stdin)
#define out() freopen("a.out", "w", stdout)
#define N 100005
#define Mod int(1e9 + 7)
inline int Read()
{
int x = 0, f = 1;
char ch = getchar();
while (ch < '0' || ch > '9')
{
if (ch == '-')
f = -1;
ch = getchar();
}
while (ch >= '0' && ch <= '9')
{
x = x * 10 + ch - 48;
ch = getchar();
}
return x * f;
}
using namespace std;
vector<int> G[N];
bool color[N];
int ans = 0;
void dfs1(int u, int fa, bool colour)
{
color[u] = colour;
for (auto v : G[u])
{
if (v != fa)
dfs1(v, u, !colour);
}
}
void dfs2(int u, int fa, int cnt)
{
if (cnt % 2 == 0)
{
ans++;
}
for (auto v : G[u])
{
if (v != fa)
dfs2(v, u, cnt + 1);
}
}
int main()
{
// read();
// out();
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int n = Read();
for_(i, 1, n - 1)
{
int u = Read(), v = Read();
G[u].push_back(v);
G[v].push_back(u);
}
dfs1(1, 0, 0);
for_(i, 1, n)
{
if(color[i] == 0)
{
dfs2(i, 0, 0);
break;
}
}
for_(i, 1, n)
{
if(color[i] == 0)
{
cout << ans << " ";
}
else
{
cout << n - ans << " ";
}
}
return 0;
}