跳到正文

个人记录

111

yujiatian约 2 分钟
原文
文章信息与版本

文章信息

收录
2026年7月10日
更新
2026年7月26日
篇幅
约 2 分钟

版本

  1. v2当前
  2. v1
C++
#include<bits/stdc++.h>
using namespace std;
struct node{
	int to,nxt;
}e[200010];
int h[100010];
int ans=0;
int s,t;
int pre[100010];
int d[100010];
int cnt=0;
inline int rd(){
	int x=0,f=1;char ch=getchar();
	while (ch<'0'||ch>'9'){if (ch=='-') f=-1;ch=getchar();}
	while (ch>='0'&&ch<='9'){x=x*10+ch-48;ch=getchar();}
	return x*f;
}
void write(long long x){
    if(x<0){
    	putchar('-');
		x=-x;
	}
    static char buf[20];
    int p=0;
    do{
        buf[p++]=x%10+'0';
        x/=10;
    }while(x);
    while(p){
    	putchar(buf[--p]);
	}
}
void add(int u,int v){
	e[cnt]={v,h[u]};
	h[u]=cnt++;
}
void dfs(int u,int fa){
	pre[u]=fa;
	for(int i=h[u];i;i=e[i].nxt){
		int v=e[i].to;
		if(v==fa)continue;
		d[v]=d[u]+1;
		if(ans<d[v]){
			ans=max(ans,d[v]);
			t=v;
		}
		dfs(v,u);
	}
}
int main(){
	int n;
	cin>>n;
	for(int i=1;i<n;i++){
		int u,v;
		cin>>u>>v;
		add(u,v);
		add(v,u);
	}
	dfs(1,0);
	s=t;
	ans=0;
	d[s]=0;
	dfs(s,0);
	for(int i=1;i<=(ans/2);i++){
		t=pre[t];
	}
	cout<<t; 
	if(ans&1)cout<<' '<<pre[t]<<endl;
	return 0;
}
原文