跳到正文

个人记录

11

AC_Seed约 4 分钟
原文
文章信息与版本

文章信息

发布
2026年10月23日
收录
2026年10月23日
更新
2026年10月23日
篇幅
约 4 分钟

版本

  1. v1当前
C++
#include<bits/stdc++.h>
using namespace std;
const int maxn=6e5+5;
struct node{
	int x,y,z;
};
vector<int>G[maxn];
int n;
bool vis[maxn];
int dp[maxn][21];
int dep[maxn];
int maxi=0,st=0,ed=0;
int LCA(int x,int y){
	if(dep[x]<=dep[y]) swap(x,y);
	for(int i=20;i>=0;i--){
		if(dep[dp[x][i]]>=dep[y]){
			x=dp[x][i];
		}
	}
	if(x==y){
		return x;
	}
	for(int i=20;i>=0;i--){
		if(dp[x][i]!=dp[y][i]){
			x=dp[x][i];
			y=dp[y][i];
		}
	}
	return dp[x][0];
}
void dfs(int x,int fa){
	dep[x]=dep[fa]+1;
	dp[x][0]=fa;
	for(int i=0;i<G[x].size();i++){
		int v=G[x][i];
		if(v==fa) continue;
		dfs(v,x); 
	}
	return ;
}
void init(){
	for(int j=1;j<=20;j++){
		for(int i=1;i<=n;i++){
			dp[i][j]=dp[dp[i][j-1]][j-1];
		}
	}
	return ;
}
void dfs2(int x,int fa,int len){
	if(len>maxi){
		maxi=len;
		ed=x;
	}
	else if(len==maxi&&ed<x){
		ed=x;
	}
	for(int i=0;i<G[x].size();i++){
		int v=G[x][i];
		if(v==fa) continue;
		if(vis[v]) continue;
		dfs2(v,x,len+1);
	}
	return ;
}
bool cmp(node q,node h){
	if(q.x!=h.x) return q.x>h.x;
	if(q.y!=h.y) return q.y>h.y;
	return q.z>h.z;
}
void work(){
	cin>>n;
	for(int i=0;i<=n+1;i++){
		G[i].clear();
		vis[i]=false;
	}
	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);
	init();
	vector<node>answer;
	for(int i=n;i>=1;i--){
		if(!vis[i]){
			maxi=0;
			st=i;
			ed=-1;
			dfs2(i,0,0);
			maxi=0;
			st=ed;
			ed=-1;
			dfs2(st,0,0);
			if(st==0||ed==-1) continue;
			int lca=LCA(st,ed);
			int t=st;
			while(t!=lca&&t){vis[t]=true;t=dp[t][0];}
			t=ed;
			while(t!=lca&&t){vis[t]=true;t=dp[t][0];}
			vis[lca]=true;
			answer.push_back({maxi+1,max(st,ed),min(st,ed)});
		}
	}
	sort(answer.begin(),answer.end(),cmp);
	for(int i=0;i<answer.size();i++) cout<<answer[i].x<<" "<<answer[i].y<<" "<<answer[i].z<<" ";
	cout<<"\n";
	return ;
}
int main(){
	//freopen("apple.in","r",stdin);
	//freopen("apple.out","w",stdout);
	int T;
	cin>>T;
	while(T--) work(); 
	return 0;
}
/*
要求A的字典序最大

首位尽可能大
优先考虑直径
如果有多条直径,优先找编号较大的点
重复上面过程
 
*/ 
原文