随机游走

112 篇文章 0 订阅

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

#include<bits/stdc++.h>
#define ll long long
using namespace std;
struct Edge
{
 int to;
 int next;
}e[200005];
int n,m,edgenum,head[100005],d[100005],pa[100005];
ll f[100005],g[100005],ans,maxup[100005],maxdown[100005];
ll tmp[100005],top,max1[100005],max2[100005],tmp2[100005];
void add(int u,int v)
{
 e[++edgenum].to=v;
 e[edgenum].next=head[u];
 head[u]=edgenum;
}
void dfs_f(int node)
{
 for(int hd=head[node];hd;hd=e[hd].next)
 {
  int to=e[hd].to;
  if(to==pa[node])continue;
  pa[to]=node;
  dfs_f(to);
  f[node]+=f[to];
 }
 f[node]+=d[node];
}
void dfs_g(int node)
{
 if(node!=1)g[node]=g[pa[node]]+f[pa[node]]-f[node];
 for(int hd=head[node];hd;hd=e[hd].next)
 {
  int to=e[hd].to;
  if(to==pa[node])continue;
  dfs_g(to);
 }
}
void dfs_tot(int node)
{
 for(int hd=head[node];hd;hd=e[hd].next)
 {
  int to=e[hd].to;
  if(to==pa[node])continue;
  dfs_tot(to);
  maxup[node]=max(maxup[node],maxup[to]+f[to]);
  maxdown[node]=max(maxdown[node],maxdown[to]+g[to]);
 }
 top=0;
 for(int hd=head[node];hd;hd=e[hd].next)
 {
  int to=e[hd].to;
  if(to==pa[node])continue;
  tmp[++top]=maxup[to]+f[to];
  tmp2[top]=maxdown[to]+g[to];
 }
 for(int i=1;i<=top;i++)
   max1[i]=max(max1[i-1],tmp[i]);
 max2[top+1]=0;
 for(int i=top;i>=1;i--)
   max2[i]=max(max2[i+1],tmp[i]);
 for(int i=1;i<=top;i++)
   ans=max(ans,tmp2[i]+max(max1[i-1],max2[i+1]));
}
int main()
{
 scanf("%d",&n);
 for(int i=1;i<n;i++)
 {
  int u,v;
  scanf("%d%d",&u,&v);
  add(u,v);
  add(v,u);
  d[u]++;
  d[v]++;
 }
 dfs_f(1);
 dfs_g(1);
 dfs_tot(1);
 printf("%lld.00000\n",ans);
 return 0;
}

来源:zr

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值