UVa 11307

another tree dp problem, solved it until I see other's solution
state:
    dp[i][j] - minimum color sum at node i colored color j
transition:
    dp[i][j]+=min(dp[k][l]), for all k is i's child and for all l of 15 colors
so the dfs method would be like
void dfs(int current, int parent) {
    if (sizeof(adj[current])) { /* internal node */
        for (int i=1; i<=15; i++) {
            dp[current][i]=i;
        }
        for (int i=0; i<sizeof(adj[current]); i++) {
            int child=adj[current][i];
            if (child==parent) continue; /* avoid cycle */
            dfs(child, current);
            for (int j=1; j<=15; j++) {
                int tmp=INF;
                for (int k=1; k<=15; k++) {
                    tmp=min(tmp, dp[child][k]);
                }
                dp[current][j]+=tmp;
            }
        }
    } else { /* leaf node */
        for (int i=1; i<=15; i++) {
            dp[current][i]=i;
        }
    }
}
and the target state is min(dp[k][i]), for any arbitrary node k as root, and for all i of 15 colors
don't know why it's 15 colors, maybe it's tried out?

No comments :

Post a Comment