题目描述
YJC最近在学习图的有关知识。今天,他遇到了这么一个概念:随机游走。随机游走指每次从相邻的点中随机选一个走过去,重复这样的过程若干次。YJC很聪明,他很快就学会了怎么跑随机游走。为了检验自己是不是欧洲人,他决定选一棵树,每条边边权为1,选一对点s和t,从s开始随机游走,走到t就停下,看看要走多长时间。但是在走了10000000步之后,仍然没有走到t。YJC坚信自己是欧洲人,他认为是因为他选的s和t不好,即从s走到t的期望距离太长了。于是他提出了这么一个问题:给一棵n个点的树,问所有点对(i,j)(1≤i,j≤n)中,从i走到j的期望距离的最大值是多少。YJC发现他不会做了,于是他来问你这个问题的答案。
处理
对每个点我们处理两个值f和g。下面的d[x]表示一个点的度数。
f[x]表示从x走到x的父亲的期望步数。
那么f[x]=1/d[x]∗1+1/d[x]∗∑j是x儿子f[j]+f[x]+1
移项化简得f[x]=d[x]+∑j是x儿子f[j]
g[x]表示从x的父亲走到x的期望步数。y表示x的父亲。
那么g[x]=1/d[y]∗1+1/d[y]∗(1+g[y]+g[x])+∑j是y儿子但不是x1+f[j]+g[x]
移项化简得g[x]=d[y]+g[y]+∑j是y儿子但不是xf[j]
两遍dfs求得f和g。
最长链
树上每条路径u->v可以表示为u->w->v,w为lca(u,v)
现在枚举w,尝试求得这条经过w的最长链。
和求直径有些类似,求出向下不相交的f和g最长和次长链,如果f最长链和g最长链不相交那么就是它们加起来,否则f或g要有一个取次长链。
再来一遍dfs搞定。
#include<cstdio>
#include<algorithm>
#define fo(i,a,b) for(i=a;i<=b;i++)
using namespace std;
typedef long long ll;
const int maxn=100000+10;
ll f[maxn],g[maxn],f1[maxn],f2[maxn],g1[maxn],g2[maxn];
int f3[maxn],g3[maxn],d[maxn];
int h[maxn],go[maxn*2],next[maxn*2];
int i,j,k,l,t,n,m,tot;
ll ans;
int read(){
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-'0';
ch=getchar();
}
return x*f;
}
void add(int x,int y){
go[++tot]=y;
next[tot]=h[x];
h[x]=tot;
}
void dfs(int x,int y){
int t=h[x];
ll l=0;
while (t){
if (go[t]!=y){
dfs(go[t],x);
l+=f[go[t]];
}
t=next[t];
}
f[x]=(ll)d[x]+l;
}
void dg(int x,int y){
int t=h[x];
ll l=0;
while (t){
if (go[t]!=y) l+=f[go[t]];
t=next[t];
}
t=h[x];
while (t){
if (go[t]!=y){
g[go[t]]=(ll)d[x]+l-f[go[t]]+g[x];
dg(go[t],x);
}
t=next[t];
}
}
void solve(int x,int y){
int t=h[x];
while (t){
if (go[t]!=y){
solve(go[t],x);
if (f1[go[t]]+f[go[t]]>f1[x]){
f2[x]=f1[x];
f1[x]=f1[go[t]]+f[go[t]];
f3[x]=go[t];
}
else if (f1[go[t]]+f[go[t]]>f2[x]) f2[x]=f1[go[t]]+f[go[t]];
if (g1[go[t]]+g[go[t]]>g1[x]){
g2[x]=g1[x];
g1[x]=g1[go[t]]+g[go[t]];
g3[x]=go[t];
}
else if (g1[go[t]]+g[go[t]]>g2[x]) g2[x]=g1[go[t]]+g[go[t]];
}
t=next[t];
}
if (f3[x]!=g3[x]) ans=max(ans,f1[x]+g1[x]);
else ans=max(ans,max(f1[x]+g2[x],f2[x]+g1[x]));
}
int main(){
freopen("rw.in","r",stdin);freopen("rw.out","w",stdout);
n=read();
fo(i,1,n-1){
j=read();k=read();
d[j]++;d[k]++;
add(j,k);add(k,j);
}
dfs(1,0);
dg(1,0);
solve(1,0);
printf("%lld.00000\n",ans);
}

5万+

被折叠的 条评论
为什么被折叠?



