随机游走

版权声明:未经过同意不得转载 https://blog.csdn.net/qq_42500298/article/details/83090418

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

#include<bits/stdc++.h>
#define N 110000
#define inf 1e9+7
#define ll long long
using namespace std;
inline int read()
{
    int x=0,flag=1;
    char ch=0;
    while(!isdigit(ch))
 {
  ch=getchar();
  if(ch=='-')
   flag=-1;
 }
    while(isdigit(ch))
 {
  x=(x<<3)+(x<<1)+ch-'0';
  ch=getchar();
 }
    return x*flag;
}
struct edge
{
 int to;
 int nxt;
 double w;
}e[N*2];
int num,head[N];
inline void add(int x,int y)
{
 num++;
 e[num].to=y;
 e[num].nxt=head[x];
 head[x]=num;
}
int d[N],dep[N];
double ans,f[N],g[N],up[N],down[N];
void dfs(int x,int fa)
{
 f[x]=d[x];
 dep[x]=dep[fa]+1;
 for(int i=head[x];i;i=e[i].nxt)
 {
  int to=e[i].to;
  if(to==fa)
   continue;
  dfs(to,x);
  f[x]+=f[to];
 }
 if(x==1)
  f[x]=0; 
}
void solve(int x,int fa)
{
 g[x]+=g[fa]+d[fa];
 if(x==1)g[x]=0;
 double tot=0;
 for(int i=head[x];i;i=e[i].nxt)
 {
  int to=e[i].to;
  if(to==fa)
   continue;
  tot+=f[to];
 }
 for(int i=head[x];i;i=e[i].nxt)
 {
  int to=e[i].to;
  if(to==fa)
   continue;
  g[to]+=tot-f[to];
  solve(to,x);
 }
}
void work(int x,int fa)
{
 for(int i=head[x];i;i=e[i].nxt)
 {
  int to=e[i].to;
  if(to==fa)
   continue;
  work(to,x);
  ans=max(ans,down[x]+up[to]+f[to]);
  ans=max(ans,up[x]+down[to]+g[to]);
  up[x]=max(up[x],up[to]+f[to]);
  down[x]=max(down[x],down[to]+g[to]);  
 }
}
int main()
{
 int n,i,x,y;
 n=read();
 for(i=1;i<=n-1;i++)
 {
  x=read();
  y=read();
  add(x,y);
  add(y,x);
  d[x]++;
  d[y]++;
 }
 dfs(1,1);
 solve(1,1);
 work(1,1);
 printf("%.5lf",ans);
 return 0;
}

来源:zr

猜你喜欢

转载自blog.csdn.net/qq_42500298/article/details/83090418
今日推荐