hdu1054树形DP

hdu1054树形DP
#include <cstdio>
#include <cstring>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
const int maxn = 1555;
vector<int> G[maxn];
int n;
int dp[maxn][2];
bool vis[maxn];
void dfs(int u) {
    vis[u] = 1;
    int sz = G[u].size();
    for(int i=0;i<sz;i++) {
        int v = G[u][i];
        if(vis[v]) continue;
        dfs(v);
        dp[u][0] += dp[v][1];
        dp[u][1] += min(dp[v][1],dp[v][0]);   
    }   
}
int main() {
    while(~scanf("%d",&n)) {
        for(int i=0;i<n;i++) G[i].clear();
        int u,num,v;
        for(int i=0;i<n;i++) dp[i][0]=0,dp[i][1]=1,vis[i]=0;
        for(int i=0;i<n;i++) {
            scanf("%d:(%d)",&u,&num);
            while(num--) {
                scanf("%d",&v);
                G[u].push_back(v);
                G[v].push_back(u);   
            }   
        }   
        dfs(0);
        int ans = min(dp[0][0],dp[0][1]);
        printf("%d\n",ans);
    }
    return 0;   
}

你可能感兴趣的:(hdu1054树形DP)