叶子的颜色---经典树上dp
挺简单的一个dp
#include<iostream> #include<cstring> #include<cstdio> #include<algorithm> #include<vector> #define maxn 10100 using namespace std; const int INF = 0x3f3f3f3f; vector<int>G[maxn]; void insert(int be, int en) { G[be].push_back(en); } int n, m; int h[maxn]; int b[maxn]; int vis[maxn]; int dfs(int x, int fa) { h[x] = 1; b[x] = 1; if (vis[x] == 0) { b[x] = INF; } if (vis[x] == 1) { h[x] = INF; } for (int i = 0; i < G[x].size(); i++) { int p = G[x][i]; if (p == fa) continue; dfs(p, x); h[x] += min(b[p], h[p] - 1); b[x] += min(h[p], b[p] - 1); } return 0; } int main() { memset(vis, -1, sizeof(vis)); scanf("%d %d", &n, &m); int op; for (int i = 1; i <= m; i++) { scanf("%d", &op); vis[i] = op; } int be, en; int root = n; for (int i = 1; i < n; i++) { scanf("%d %d", &be, &en); insert(be, en); insert(en, be); } dfs(n, -1); printf("%d\n", min(h[n], b[n])); return 0; }
寻找真正的热爱