The general idea is the same as in the Great White Book, but it is not very clear how the decision part of the book is explained, so I am here to explain my decision-making ideas.
First, D (I,J) represents a subtree of the root node I, when its parent node is J (j=0 or 1), the minimum value of x (the meaning Book of X is explained), the case of the child tree root node and the parent node is connected to the edge of the situation is counted. Next, each tree in the forest is traversed, and the root node of each tree is specially processed, and then the tree is deeply first searched for Dfs (i).
For D[i][0], because the parent node of the current subtree node i is 0, the state of the child tree root node must be 1, then D[i][0]=sum{d[k][1]|k is the child node of I}+m+1. However, for d[i][1] There are two situations to discuss: When I is 1 o'clock,D1=sum{d[k][1]|k is the child of I}+m, when I is 0 o'clock,d0=sum{d[k][0]|k is the child node of I}+1, then d[i][1]=min (D0,D1). Finally, each tree's root node is 1 and itself 0, respectively, plus the sum{d[k][j]|k for the corresponding root node of the child node} can be. See the code for detailed answers.
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #define MAX 1000+5 #define M 2000using namespace Std;int t,n,m,x;int g[max][max],vis[max],d[max][2];void dfs (int); int main () {Cin>> ; T while (t--) {cin>>n>>m; memset (g,0,sizeof (G)); x=0; int A, B; for (int i=0;i<m;++i) {cin>>a>>b; G[a][b]=g[b][a]=1; } memset (Vis,0,sizeof (VIS)); Memset (d,0,sizeof (d)); for (int i=0;i<n;++i) if (!vis[i]) {vis[i]=1; int d0=0,d1=0; for (int j=0;j<n;++j) if (G[i][j]) {DFS (j); D0+=D[J][0]; D1+=D[J][1]; } d1+=m; X+=min (D0,D1); } cout<<x/m<< "" <<m-x%M<< "" <<x%M<<endl; } return 0;} void dfs (int root) {int leaf=1,d0=0,d1=0; Vis[root]=1; for (int i=0;i<n;++i) if (!vis[i]&&g[root][i]) {leaf=0; DFS (i); D[ROOT][0]+=D[I][1]; D0+=D[I][0]; D1+=D[I][1]; } d[root][0]+=m+1; D[root][1]=min (d1+m,d0+1); if (leaf) {//leaf node special treatment d[root][0]=m+1; D[root][1]=1; } return;
UVa placing lampposts-tree DP