随笔 - 531  文章 - 0  评论 - 3  阅读 - 10201 

 换根dp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include<iostream>
#include<algorithm>
#include<cstring>
#include<queue>
#define IOS std::ios::sync_with_stdio(0)
using namespace std;
 #define int long long
const int  N=2e5+20;
 int n,sz[N],f[N],G[N];
 vector<int> g[2*N];
  
 void dfs1(int x,int fa){
    sz[x]=1;
    for(auto y:g[x]){
        if(y==fa) continue; dfs1(y,x);
        sz[x]+=sz[y];
    }
    int s=0;
    for(auto y:g[x]){
        if(y==fa) continue;
        s+=f[y];
    }
    f[x]=s+sz[x];
 }
 void dfs2(int x,int fa){
     
    for(auto y:g[x]){
        if(y==fa) continue; G[y]=G[x]+n-2*sz[y];
        dfs2(y,x);
    }
 }
 signed main(){
    int i,x,y;
    cin>>n;
    for(i=1;i<n;i++)
        cin>>x>>y,g[x].push_back(y),g[y].push_back(x);
     
    dfs1(1,0); G[1]=f[1];
    dfs2(1,0);
    int ans=0;
    for(i=1;i<=n;i++) ans=max(ans,G[i]);
    cout<< ans <<endl;
 }

 

posted on   towboat  阅读(9)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探
点击右上角即可分享
微信分享提示