大意: 给定树, 求两个点, 使得所有其他的点到两点的最短距离的最大值尽量小.
二分答案转为判定选两个点, 向外遍历$x$的距离是否能遍历完整棵树. 取直径两段距离$x$的位置bfs即可.
#include <iostream> #include <iostream> #include <algorithm> #include <cstdio> #include <math.h> #include <set> #include <map> #include <queue> #include <string> #include <string.h> #include <bitset> #define REP(i,a,n) for(int i=a;i<=n;++i) #define PER(i,a,n) for(int i=n;i>=a;--i) #define hr putchar(10) #define pb push_back #define lc (o<<1) #define rc (lc|1) #define mid ((l+r)>>1) #define ls lc,l,mid #define rs rc,mid+1,r #define x first #define y second #define io std::ios::sync_with_stdio(false) #define endl ' ' #define DB(a) ({REP(__i,1,n) cout<<a[__i]<<' ';hr;}) using namespace std; typedef long long ll; typedef pair<int,int> pii; const int P = 1e9+7, INF = 0x3f3f3f3f; ll gcd(ll a,ll b) {return b?gcd(b,a%b):a;} ll qpow(ll a,ll n) {ll r=1%P;for (a%=P;n;a=a*a%P,n>>=1)if(n&1)r=r*a%P;return r;} ll inv(ll x){return x<=1?1:inv(P%x)*(P-P/x)%P;} inline int rd() {int x=0;char p=getchar();while(p<'0'||p>'9')p=getchar();while(p>='0'&&p<='9')x=x*10+p-'0',p=getchar();return x;} //head const int N = 2e5+100; int n, r1, r2, ans1, ans2; vector<int> g[N]; int vis[N], dis[N], fa[N], s[N]; vector<int> d1, d2; queue<int> q; int bfs(int x) { REP(i,0,n+10) vis[i]=0; REP(i,0,n+10) fa[i]=0; vis[x] = 1, q.push(x); while (!q.empty()) { x = q.front();q.pop(); for (int i=0,j=g[x].size(); i<j; ++i) { int y = g[x][i]; if (!vis[y]) vis[y] = 1, fa[y]=x, q.push(y); } } return x; } void init() { r1 = bfs(1), r2 = bfs(r1); *s = 0; for (int i=r2; i; i=fa[i]) s[++*s]=i; } int chk(int x) { ans1=d1[x],ans2=d2[x]; REP(i,0,n+10) vis[i]=0; REP(i,0,n+10) dis[i]=1e9; dis[ans1]=dis[ans2]=0; q.push(ans1),q.push(ans2); while (q.size()) { int u = q.front(); q.pop(); if (vis[u]) continue; vis[u] = 1; if (dis[u]==x) continue; for (int i=0,j=g[u].size(); i<j; ++i) { int v = g[u][i]; if (!vis[v]) { q.push(v); dis[v]=min(dis[v],dis[u]+1); } } } REP(i,1,n) if (!vis[i]) return 0; return 1; } void work() { n=rd(); REP(i,1,n+10) g[i].clear(); REP(i,2,n) { int u=rd(), v=rd(); g[u].pb(v),g[v].pb(u); } if (n==2) return puts("0 1 2"),void(); if (n==3) return puts("1 1 2"),void(); init(); if (*s<=3) return printf("1 %d %d ",s[1],s[2]),void(); d1.clear(),d2.clear(); REP(i,1,*s) d1.pb(s[i]); PER(i,1,*s) d2.pb(s[i]); int l=1,r=*s-1,ans; while (l<=r) { if (chk(mid)) ans=mid,r=mid-1; else l=mid+1; } chk(ans); while (ans1==ans2) { if (++ans2>n) ans2=1; } printf("%d %d %d ",ans,ans1,ans2); } int main() { int t; scanf("%d", &t); while (t--) work(); }