求助
查看原帖
求助
218188
ParanoidMO楼主2021/8/16 15:45
#include<bits/stdc++.h>
using namespace std;
const int maxn=100010;
vector<int> G[maxn];
int dpt, depth[maxn], s, n, f[maxn], rt, l[maxn], ans, k;
bool vis[maxn];

void dfs(int x, int fa)
{
	if (vis[x]) return;
	vis[x] = 1;
	f[x] = fa;
	depth[x] = depth[fa] + 1;
	if (depth[x] > dpt)
	{
		dpt = depth[x];
		s = x;
	}
	for (int i=0; i<G[x].size(); i++)
	{
		int v = G[x][i];
		if (v != fa) dfs(v, x);
	}
}

int main()
{
	ios::sync_with_stdio(false);
	cin.tie(0); cout.tie(0);
	cin>>n>>k;
	for (int i=1; i<n; i++)
	{
		int u, v; cin>>u>>v;
		G[u].push_back(v);
		G[v].push_back(u);
	}
	dfs(1, 0);
	memset(vis, 0, sizeof(vis));
	memset(depth, 0, sizeof(depth));
	memset(f, 0, sizeof(f));
	dpt = 0;
	dfs(s, 0);
	rt = s;
	for (int i=1; i<=dpt/2; i++) {
		rt=f[rt];
	}
	memset(vis, 0, sizeof(vis));
	memset(depth, 0, sizeof(depth));
	memset(f, 0, sizeof(f));
	dpt = 0;
	dfs(rt, 0);
	for (int i=1; i<=n; i++) l[i] = dpt-depth[i];
	sort(l+1, l+1+n);
	cout<<l[n-k]+1;
	system("pause");
}
2021/8/16 15:45
加载中...