链接
题解
我先找到整棵树的重心,假设是 G G G
假设 1 1 1到 G G G这条链上的点序列为 a 1 , a 2 , . . . , a k a_1,a_2,...,a_k a1,a2,...,ak,其中 a 1 = 1 , a k = G a_1=1,a_k=G a1=1,ak=G
那么现在我把 a 1 a_1 a1拿掉,计算以 a 2 a_2 a2为根的树的重心的时候,新的重心肯定在 G G G的子树里面
如果我一直这样不停的拿掉最上面的点,那么 G G G就会一直下沉,直到抵达某个叶子节点
稍微想一下,就会发现 G G G行走的轨迹就是一条重链
所以我只要把每一条重链都拿出来跑一下就行了
时间复杂度是 O ( n ) O(n) O(n)的
代码
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#define iinf 0x3f3f3f3f
#define linf (1ll<<60)
#define eps 1e-8
#define maxn 1000010
#define maxe 1000010
#define cl(x) memset(x,0,sizeof(x))
#define rep(i,a,b) for(i=a;i<=b;i++)
#define drep(i,a,b) for(i=a;i>=b;i--)
#define em(x) emplace(x)
#define emb(x) emplace_back(x)
#define emf(x) emplace_front(x)
#define fi first
#define se second
#define de(x) cerr<<#x<<" = "<<x<<endl
using namespace std;
using namespace __gnu_pbds;
typedef long long ll;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
ll read(ll x=0)
{
ll c, f(1);
for(c=getchar();!isdigit(c);c=getchar())if(c=='-')f=-f;
for(;isdigit(c);c=getchar())x=x*10+c-0x30;
return f*x;
}
struct Graph
{
int etot, head[maxn], to[maxe], next[maxe], w[maxe];
void clear(int N)
{
for(int i=1;i<=N;i++)head[i]=0;
etot=0;
}
void adde(int a, int b, int c=0){to[++etot]=b;w[etot]=c;next[etot]=head[a];head[a]=etot;}
#define forp(_,__) for(auto p=__.head[_];p;p=__.next[p])
}G;
struct Heavy_Light_Decomposition
{
int size[maxn], top[maxn], tid[maxn], tim, untid[maxn], depth[maxn], son[maxn], fa[maxn];
void dfs1(Graph &G, int pos)
{
int p, v;
size[pos]=1;
for(p=G.head[pos];p;p=G.next[p])
{
if((v=G.to[p])==fa[pos])continue;
fa[v]=pos;
depth[v]=depth[pos]+1;
dfs1(G,v);
if(size[v]>size[son[pos]])son[pos]=v;
size[pos]+=size[v];
}
}
void dfs2(Graph &G, int pos, int tp)
{
int p, v;
top[pos]=tp;
tid[pos]=++tim;
untid[tid[pos]]=pos;
if(son[pos])dfs2(G,son[pos],tp);
for(p=G.head[pos];p;p=G.next[p])
if((v=G.to[p])!=fa[pos] and v!=son[pos])dfs2(G,v,v);
}
void run(Graph &G, int root)
{
tim=0;
depth[root]=1;
dfs1(G,root);
dfs2(G,root,root);
}
}HLD;
vector<ll> ans[maxn];
int main()
{
ll n=read(), i, j, a, b, l=1, r=1;
vector<bool> vis(n+5);
vector<ll> q(n+5);
rep(i,1,n-1)
{
a=read(), b=read();
G.adde(a,b), G.adde(b,a);
}
HLD.run(G,1);
rep(i,1,n)
{
if(HLD.top[i]!=i)continue;
ll t=i;
while(t)
{
q[r++]=t;
t = HLD.son[t];
}
// printf("# ");rep(j,l,r-1)printf("%lld ",q[j]); putchar(10);
ll G=l;
while(l!=r)
{
ll now = q[l++];
while(G<r-1 and HLD.size[q[G+1]] > HLD.size[now]/2)
{
G++;
}
if(G<r-1 and HLD.size[q[G+1]] == HLD.size[now]/2 and HLD.size[now]%2==0 )
ans[now] = vector<ll>{q[G],q[G+1]};
else
ans[now] = vector<ll>{q[G]};
}
}
rep(i,1,n)
{
sort(ans[i].begin(),ans[i].end());
if(ans[i].size()==2)
{
printf("%lld %lld\n",ans[i][0],ans[i][1]);
}
else
{
printf("%lld\n",ans[i][0]);
}
}
return 0;
}