CF911F Tree Destruction

传送门

Luogu

Solution

感性理解一下,很显然我们将直径抠出来然后删除直径外的叶子一定比其他删法更优,然后直径里面的内部消化即可。

Code

/*
  mail: mleautomaton@foxmail.com
  author: MLEAutoMaton
  This Code is made by MLEAutoMaton
*/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
#include<algorithm>
#include<queue>
#include<set>
#include<map>
#include<iostream>
using namespace std;
#define ll long long
#define REP(a,b,c) for(int a=b;a<=c;a++)
#define re register
#define file(a) freopen(a".in","r",stdin);freopen(a".out","w",stdout)
#define int ll
inline int gi(){
	int f=1,sum=0;char ch=getchar();
	while(ch>'9' || ch<'0'){if(ch=='-')f=-1;ch=getchar();}
	while(ch>='0' && ch<='9'){sum=(sum<<3)+(sum<<1)+ch-'0';ch=getchar();}
	return f*sum;
}
const int N=200010;
int n,f[N],g[N],rt1,rt2,dep[N],fa[N],in[N],Ans;
vector<int>G[N];
typedef pair<int,int> pii;
#define mp make_pair
vector<pii>ans;
void dfs1(int u,int ff){
	f[u]=f[ff]+1;
	if(f[u]>f[rt1])rt1=u;
	for(int v:G[u])if(v!=ff)dfs1(v,u);
}
void dfs2(int u,int ff){
	g[u]=g[ff]+1;
	if(g[u]>g[rt2])rt2=u;
	for(int v:G[u])if(v!=ff)dfs2(v,u);
}
void dfs3(int u,int ff){
	fa[u]=ff;dep[u]=dep[ff]+1;
	for(int v:G[u])if(v!=ff)dfs3(v,u);
}
void solve(int u,int ff){
	int son=0;
	for(int v:G[u])if(v!=ff){son++;solve(v,u);}
	if(!in[u]){
		if(dep[u]>g[u])ans.push_back(mp(rt2,u));
		else ans.push_back(mp(rt1,u));
		Ans+=max(dep[u]-1,g[u]-1);
	}
}
signed main(){
	n=gi();
	for(int i=1;i<n;i++){
		int u=gi(),v=gi();
		G[u].push_back(v);G[v].push_back(u);
	}
	dfs1(1,1);dfs2(rt1,rt1);dfs3(rt2,rt2);
	for(int i=rt1;i!=rt2;i=fa[i])in[i]=1;in[rt2]=1;
	solve(rt2,rt2);
	for(int i=rt1;i!=rt2;i=fa[i]){
		Ans+=dep[i]-1;
		ans.push_back(mp(rt2,i));
	}
	printf("%lld\n",Ans);
	for(auto now:ans)printf("%lld %lld %lld\n",now.first,now.second,now.second);
	return 0;
}
posted @ 2019-10-15 17:10  fexuile  阅读(194)  评论(2编辑  收藏  举报