[代码]codeforces 274B Zero Tree

Abstract

codeforces 274B Zero Tree

树型dp

Source

http://codeforces.com/problemset/problem/274/B

Solution

艹,发现我已经快不会写代码了…赶快发个日志表示我有在做题…

Code

#include <iostream>

#include <vector>

#include <algorithm>

using namespace std;



typedef long long ll;

typedef pair<ll, ll> pr;

pr (*mkpr)(ll, ll) = make_pair<ll, ll>;



int N;

ll x[111111];

ll ans = 0;

vector<int> adj[111111];



inline void nya(pr &a, pr b) {

    a.first = max(a.first, b.first);

    a.second = min(a.second, b.second);

}



void ae(int u, int v) {

    adj[u].push_back(v);

    adj[v].push_back(u);

}



pr solve(int p, int u) {

    int i, v;

    pr res = mkpr(0ll, 0ll);

    for (i = 0; i < adj[u].size(); ++i) {

        if ((v=adj[u][i])==p) continue;

        nya(res, solve(u, v));

    }

    x[u] -= res.first+res.second;

    if (x[u]>0ll) res.first += x[u];

    else res.second += x[u];

    return res;

}



int main() {

    int i, j, k;

    cin>>N;

    for (i = 1; i < N; ++i) {

        cin>>j>>k;

        ae(j, k);

    }

    for (i = 1; i <= N; ++i)

        cin>>x[i];

    pr ans = solve(0, 1);

    cout<<ans.first-ans.second<<'\n';

    return 0;

}

 

你可能感兴趣的:(codeforces)