Educational Codeforces Round 67 E.Tree Painting (树形dp)

Topic Link 

Meaning of the questions: After you unrooted tree, every point you can choose to become a black spot from the white point (except for the first point and the other point to be adjacent black dots), can become black spots a weight value is obtained (white dots communication block size) to ask how to make the maximum weight

Ideas: First, a determined but the root of the whole tree weight only need to simulate, so the idea is converted for the sake of which point to the root of the maximum.

This problem will need a second scan to change the root of thinking , we can start at any point to be a tree and get dp from this point gradually began to update his son node

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<string>
#include<vector>
#include<stack>
#include<bitset>
#include<cstdlib>
#include<cmath>
#include<set>
#include<list>
#include<deque>
#include<map>
#include<queue>
#define ll long long int
using namespace std;
inline ll gcd(ll a,ll b){return b?gcd(b,a%b):a;}
inline ll lcm(ll a,ll b){return a/gcd(a,b)*b;}
int moth[13]={0,31,28,31,30,31,30,31,31,30,31,30,31};
int dir[4][2]={1,0 ,0,1 ,-1,0 ,0,-1};
int dirs[8][2]={1,0 ,0,1 ,-1,0 ,0,-1, -1,-1 ,-1,1 ,1,-1 ,1,1};
const int inf=0x3f3f3f3f;
const ll mod=1e9+7;
int n;
vector<int> G [ 200007 ]; 
LL DP [ 200007 ]; // represents the contribution of all the nodes i 
LL F [ 200007 ]; i In // root weights 
LL NUMP [ 200007 ]; // son nodes (contains its own )
 void DFS ( int U, int FA) { 
    NUMP [U] = . 1 ;
     for ( int I = 0 ; I <G [U] .size (); I ++ ) {
         int V = G [U] [I];
         IF (FA == V) Continue ; 
        DFS (V, U); 
        NUMP [U] + = NUMP [V]; 
    } 
} 
void DFSS (int u,int fa){
    for(int i=0;i<G[u].size();i++){
        int v=G[u][i];
        if(v==fa) continue;
        dfss(v,u);
        dp[u]+=dp[v];
    }
    dp[u]+=nump[u];
}
void change(int u,int fa){
    for(int i=0;i<G[u].size();i++){
        int v=G[u][i];
        if(v==fa) continue;
        f[v]=f[u]-nump[v]-dp[v]+n-nump[v]+dp[v]; //核心代码
        change(v,u);
    }
}
int main(){
    ios::sync_with_stdio(false);
    cin>>n;
    for(int i=1;i<n;i++){
        int u,v; cin>>u>>v;
        G[u].push_back(v);
        G[v].push_back(u);
    }
    dfs(1,0);  
    dfss(1,0);
    f[1]=dp[1];
    change(1,0);
    ll ans=0;
    for(int i=1;i<=n;i++){
        ans=max(ans,f[i]);
    }
    cout<<ans<<"\n";
    return 0;
}

 

Guess you like

Origin www.cnblogs.com/wmj6/p/11125918.html