I am referring to this article written: http://blog.csdn.net/fsss_7/article/details/52049474
A little thought: Dp[i][0] represents the root of this point and the total number of leaves for an even number of leaves of the answer
Consider the contribution of each tree side, greedy think, it must be the number of times each tree side appears the less the better
Since the tree chain is definitely from one leaf to another, then you can think of
1: Consider the sub-tree at the edge of each tree, if there are odd number of nodes, then out of a side can be, the rest of their own matching is good
2: If it is an even number of edges, out of two, if the extra two is better than two, less than two, not in line with test instructions
DP[I][1] Represents the total number of odd points, with I as the root of the subtree, containing a chain of the best answer
Odd number is actually more than even, a chain, consider including this chain
Greedy to think, this chain as long as from a leaf node extends to its first ancestor (and this ancestor has more than one son) on the line.
DP[I][1] is the current subtree contains the optimal value of this chain, then dp[root][1] is an odd answer, Dp[root][0] is even the answer
#include <cstdio>#include<cstring>#include<vector>#include<queue>#include<map>#include<iostream>#include<algorithm>using namespaceStd;typedefLong LongLL;Const intn=1e5+5;Const intinf=0x3f3f3f3f;intT,n,head[n],tot;structedge{intV,next;} Edge[n<<1];voidAddintUintv) {EDGE[TOT].V=v; Edge[tot].next=Head[u]; Head[u]=tot++;}intd[n],son[n],dp[n][2];voidDfsintUintf) { intChild=0; son[u]=0;DP [u][0]=0; for(intI=head[u];~i;i=Edge[i].next) { intV=EDGE[I].V;if(v==f)Continue; DFS (v,u);++child;son[u]+=Son[v]; dp[u][0]+=dp[v][0]; if(son[v]&1) ++dp[u][0]; Elsedp[u][0]+=2; } for(intI=head[u];~i;i=Edge[i].next) { intV=EDGE[I].V;if(v==f)Continue; if(child>1&&son[v]==1) dp[u][1]=min (dp[u][1],dp[u][0]); if(dp[v][1]==inf)Continue; intD = ((Son[v] &1) ?1: -1); dp[u][1] = min (dp[u][1], dp[u][0]-dp[v][0] + dp[v][1] +d); } if(!child) son[u]=1;}intMain () {scanf ("%d",&T); while(t--) {scanf ("%d", &n); tot=0; memset (Head,-1,sizeof(head)); memset (Dp,inf,sizeof(DP)); memset (d,0,sizeof(d)); for(intI=1; i<n;++i) { intU,V;SCANF ("%d%d",&u,&v); Add (u,v); add (v,u);++d[u];++D[v]; } if(n==2) {printf ("1\n");Continue;} intCnt=0, Root; for(intI=1; i<=n;++i)if(d[i]!=1) root=i; Else++CNT; DFS (Root,0); if(cnt&1) printf ("%d\n", dp[root][1]); Elseprintf"%d\n", dp[root][0]); } return 0;}
View Code
HDU5758 Explorer Bo Tree DP