连通能力
对于一棵有边权的树(N 个结点 N – 1 条边的无向连通图),我们 按以下方法定义其 连通能力:
1、规定某结点的代价为它到其它结点的距离(简单路径所经过边的权值 和)的最大值;
2、代价最小的结点的代价作为这棵树的连通能力。
设某棵给定的树以 1 号结点为根,问以任意结点为根的子树的连 通能力有多大。
分析
首先看到有关于树上最长链的,能想到树的直径。然而题目中还有一个最小的要求,所以也并不是直径。
不妨将题目要求的东西定义为“树的半径”。因为既在最长链上,但又能保持和两链端的距离大致相等,向左移一步,到右边链端的值会变大,答案也会更大,同理向右移也是。所以在中间位置最优,类似带权中位数,成为既满足最长距离,也满足最小代价。
可以证明代价最小的节点一定在树的直径上,感性理解一下
树的直径?->树形dp呀
找到了直径怎么找中间那个点呢?
想到了lca里面的倍增,往上跳直径/2个长度即可
所以说知识掌握要熟练,这道题分析起来比较简单,知识点都是学过的,可就是写不来
#include<bits/stdc++.h>
#define N 1000005
using namespace std;
int first[N],next[N*2],to[N*2],w[N*2],tot;
int n,fa[N][21],f1[N],f2[N],dep[N];
int pos1[N],pos2[N],dis[N],d[N],ans[N];
int read(){
int cnt=0;char ch=0;
while(!isdigit(ch))ch=getchar();
while(isdigit(ch))cnt=cnt*10+(ch-'0'),ch=getchar();
return cnt;
}
void add(int x,int y,int z){
next[++tot]=first[x];
first[x]=tot,to[tot]=y,w[tot]=z;
}
void dfs(int cur,int f){
for(int i=1;i<=20;i++)
fa[cur][i]=fa[fa[cur][i-1]][i-1];
pos1[cur]=pos2[cur]=cur;
for(int i=first[cur];i;i=next[i]){
int t=to[i];
if(t==f) continue;
fa[t][0]=cur,dis[t]=dis[cur]+w[i],dep[t]=dep[cur]+1;
dfs(t,cur);
if(ans[t]>ans[cur]) d[cur]=d[t],ans[cur]=ans[t];
if(f1[t]+w[i]>f1[cur]){
f2[cur]=f1[cur],f1[cur]=f1[t]+w[i];
pos2[cur]=pos1[cur],pos1[cur]=pos1[t];
}
else if(f1[t]+w[i]>f2[cur]){
f2[cur]=f1[t]+w[i];
pos2[cur]=pos1[t];
}
}
int x=pos1[cur];
if(d[cur]<f1[cur]+f2[cur]){//否则答案更儿子一样
d[cur]=f1[cur]+f2[cur];
for(int i=20;i>=0;i--){
if(dep[fa[x][i]]>=dep[cur]&&f1[cur]-dis[fa[x][i]]+dis[cur]<=f2[cur]+dis[fa[x][i]]-dis[cur])
x=fa[x][i];
}
ans[cur]=f2[cur]+dis[x]-dis[cur];
if(f1[cur]-dis[fa[x][0]]+dis[cur]<ans[cur]) ans[cur]=f1[cur]-dis[fa[x][0]]+dis[cur];
}
}
int main()
{
//freopen("1.in","r",stdin);
n=read();
for(int i=1;i<=n-1;i++){
int x=read(),y=read(),z=read();
add(x,y,z),add(y,x,z);
}
dep[1]=1,dfs(1,0);
for(int i=1;i<=n;i++) printf("%d\n",ans[i]);
return 0;
}