first, it, is a tree;
so,let’s see what can you do to dfs it;
firstly, we see the root like one;
than, we diffusion the root to other node which is linked with it at first;
do the samething again untill you can not;
then, you comeback and do the thing again and again;
So our traversat is going to be;
it sounds not easy but not very hard;
the code is
#include<bits/stdc++.h>
using namespace std;
const int N = 100010, M = N * 2;
int n;
int h[n], e[M], ne[M], idx;
bool st[N]//使用bool表示这个节点是否被使用过,每个节点都只被使用一次
void add(int a, int b);
{
e[idx] = b, ne[idx] = h[a], h[a] = idx ++;
}
void dfs(int u)
{
st[u] = true;
for(int i = h[u]; i != -1; i = ne[i])//遍历到没有剩下的点为止
{
int j = e[i]
if(!st[j]) dfs(j);//如果这个点没有被收缩,那么这个点也会被加入;
}
}
int main()
{
memset(h, -1, sizeof h);
}
so, let’s look at problem and use it to solve;
code
#include<bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
int e[N << 1], ne[N << 1];
int h[N], idx, n;
int ans = N;
bool st[N];
void add(int a, int b)
{
e[idx] = b, ne[idx] = h[a], h[a] = idx ++ ;
}
int dfs(int u)
{
st[u] = true;
int sum = 0, size = 0;
for(int i = h[u]; i != -1; i= ne[i])
{
int j = e[i];
if(st[j]) continue;
int s = dfs(j);
sum += s;
size = max(size, s);
}
size = max(size, n - sum - 1);
ans = min(size, ans);
return sum + 1;
}
int main()
{
cin >> n;
memset(h, -1, sizeof h);
for(int i = 1; i < n; i ++)
{
int a, b;
cin >> a >> b;
add(a, b);//同时联通两边,转化为无向;
add(b, a);
}
dfs(1);
cout << ans << endl;
return 0;
}
𝓽𝓱𝓪𝓷𝓴𝓼
@threeWeatherMan
@是丝豆呀