题解 | #小绿的房子#
E
考察树的直径。 先随便取个点,搜出最距离此点最远节点,再以这个节点为起点,再搜一遍,最后重复一遍。搜的过程中记录一下距离是否大于2.
#include<bits/stdc++.h>
using namespace std;
const int N = 2e5 + 5;
int n;
bool vis[N];
struct node {
int to, next;
}edge[N];
int head[N], cnt;
int ans;
int mxlen;
int nod;
void add(int u, int v)//前向星记录边
{
edge[++cnt].to = v;
edge[cnt].next = head[u];
head[u] = cnt;
}
void dfs(int now, int fa, int len, int hea)
{
if (len > 2) { vis[hea] = 1; vis[now] = 1; }
if (mxlen < len) { mxlen = len; nod = now; }
for (int i = head[now]; i; i = edge[i].next)
{
int x = edge[i].to;
if (x != fa) { dfs(x, now, len + 1, hea); }
}
}
int main(void)
{
ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
cin >> n;
for (int i = 1; i < n; i++)
{
int u, v;
cin >> u >> v;
add(u, v);
add(v, u);
}
dfs(1, 0, 0, 1);
dfs(nod, 0, 0, nod);
dfs(nod, 0, 0, nod);
for (int i = 1; i <= n; i++)
if (!vis[i])ans++;
cout << ans;
}