Luo Gu P2996 [USACO10NOV] Visit Visiting Cows Cows

topic

Tree dp

Set f [i] [j] denotes the i-th node went maximum weight

j 0/1 indicates that the click or do not choose

If you do not choose it from this point of his sub-tree of the election or do not choose the largest election

If you click on the tree with his son not vote

f[x][0] += max(f[to][1], f[to][0]);

f[x][1] += f[to][0];

Note 2 to the second dimension to open

Code:

// set f [i] [j] denotes the i-th node is selected from a maximum priority value 
#include <cstdio> 
#include <the iostream>
 the using  namespace STD;
 const  int N = 500 010 ;
 int F [N] [ 2 ], n-, head [N << . 1 ], CNT;
 struct Node {
     int NXT, to;
} And [C];
int read() {
    int s = 0, w = 1;
    char ch = getchar();
    while(!isdigit(ch)) {if(ch == '-') w = -1; ch = getchar();}
    while(isdigit(ch)) {s = s * 10 + ch - '0'; ch = getchar();}
    return s * w;
}
void add(int x, int y) {
    e[++cnt].nxt = head[x];
    e [cnt] .to = y;
    head[x] = cnt;
}
void dfs(int x, int fa) {
    f[x][1] = 1;
    for(int i = head[x]; i; i = e[i].nxt) {
        int v = e[i].to;
        if(v != fa) {
            dfs(v, x);
            f[x][0] += max(f[v][0], f[v][1]);
            f[x][1] += f[v][0];    
        } 
    }
}
int main () {
    n = read();
    for(int i = 1, x, y; i < n; i++) {
        x = read(), y = read();
        add(x, y), add(y, x);
    }
    dfs(1, 0);
    cout << max(f[1][1], f[1][0]) << endl;
    return 0;
}

 

Guess you like

Origin www.cnblogs.com/yanxiujie/p/11720768.html