\[ dp[u][0]=\sum_{v{\in}son(u)}Min{\{}dp[v][0],dp[v][1],dp[v][2]{\}};\dp[u][1]=\sum_{v{\in}son(u)}Min(dp[v][0],dp[v][2]); \]
\[ \sum_{w{\in}son(u),w!=v}Min(dp[w][0],dp[w][2])=dp[u][1]-Min(dp[v][0],dp[v][2]) \]
\[ dp[u][2]=Min_{v{\in}son(u)}{\{}dp[u][1]-Min(dp[v][0],dp[v][2])+dp[v][0]{\}} \]
#include<iostream>
#include<cstring>
#include<cstdio>
#define maxn 10001
using namespace std;
struct edge{
int to,next;
edge(){}
edge(const int &_to,const int &_next){ to=_to,next=_next; }
}e[maxn<<1];
int head[maxn],k;
int dp[maxn][3],n;
inline int read(){
register int x(0),f(1); register char c(getchar());
while(c<'0'||'9'<c){ if(c=='-') f=-1; c=getchar(); }
while('0'<=c&&c<='9') x=(x<<1)+(x<<3)+(c^48),c=getchar();
return x*f;
}
inline void add(const int &u,const int &v){ e[k]=edge(v,head[u]),head[u]=k++; }
void dfs(int u,int pre){
dp[u][0]=1,dp[u][2]=0x3f3f3f3f;
for(register int i=head[u];~i;i=e[i].next){
int v=e[i].to;
if(v==pre) continue;
dfs(v,u);
dp[u][0]+=min(dp[v][0],min(dp[v][1],dp[v][2]));
dp[u][1]+=min(dp[v][0],dp[v][2]);
}
for(register int i=head[u];~i;i=e[i].next){
int v=e[i].to;
if(v!=pre) dp[u][2]=min(dp[u][2],dp[u][1]-min(dp[v][0],dp[v][2])+dp[v][0]);
}
}
int main(){
memset(head,-1,sizeof head);
n=read();
for(register int i=1;i<n;i++){
int u=read(),v=read();
add(u,v),add(v,u);
}
dfs(1,1);
printf("%d\n",min(dp[1][0],dp[1][2]));//1没有父亲所以不存在dp[1][1]
return 0;
}
原文:https://www.cnblogs.com/akura/p/10986852.html