树形dp
dp[x][0]表示x点父亲没选,dp[x][1]表示x点父亲选了,然后dp[x][0]=max(sigma(dp[c[x]][0]),sigma(dp[c[x]][1])) dp[x][1]=sigma(dp[c[x][0]])
答案就是dp[1][0] 根没有父亲
#include<bits/stdc++.h> using namespace std; const int N = 50010; int n,cnt = 1; int head[N], dp[N][2]; struct edge { int nxt, to; } e[N << 1]; inline void link(int u, int v) { e[++cnt].nxt = head[u]; head[u] = cnt; e[cnt].to = v; } void dfs(int u, int last) { int sum_0 = 0, sum_1 = 0; for(int i = head[u]; i; i = e[i].nxt) { if(e[i].to == last) continue; dfs(e[i].to, u); sum_0 += dp[e[i].to][0]; sum_1 += dp[e[i].to][1]; } dp[u][0] = max(sum_0, sum_1 + 1); dp[u][1] = sum_0; } int main() { scanf("%d", &n); for(int i = 1; i < n; ++i) { int u, v; scanf("%d%d", &u, &v); link(u, v); link(v, u); } dfs(1, 0); printf("%d\n", dp[1][0]); return 0; }
时间: 2024-10-09 01:23:47