Codeforces - Tree with Small Distances

题目链接:Codeforces - Tree with Small Distances


贪心+瞎搞。

每次从最远的点连接,每次标记附近的点,保证不再被选。


AC代码:

#pragma GCC optimize("-Ofast","-funroll-all-loops")
#include<bits/stdc++.h>
//#define int long long
using namespace std;
const int N=2e5+10;
int n,dep[N],vis[N],f[N],res;
vector<int> g[N];	priority_queue<pair<int,int>> q;
void dfs(int x,int fa){
	dep[x]=dep[fa]+1;	f[x]=fa;
	for(auto to:g[x])	if(to!=fa)	dfs(to,x);
}
signed main(){
	cin>>n;
	for(int i=1,x,y;i<n;i++)	
		scanf("%d %d",&x,&y),g[x].push_back(y),g[y].push_back(x);
	dfs(1,1);
	for(int i=1;i<=n;i++)	if(dep[i]>3)	q.push({dep[i],i});
	while(q.size()){
		int u=q.top().second;	q.pop();	if(vis[u])	continue;
		res++;	vis[u]=vis[f[u]]=1;	
		for(auto x:g[f[u]])	vis[x]=1;
	}
	cout<<res;
	return 0;
}
发布了604 篇原创文章 · 获赞 242 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/weixin_43826249/article/details/104382315