树上的点可以涂成黑色或白色,求最少的黑色点,使得任意白点只和一个黑点相连

 

 

白点只和一个黑点相连,所以对于节点x, 不仅考虑 x ,son[x] 的情况,还有 x,father[x] 

 

 f[x][3]   黑点个数

 

0: x 为 黑点

1:x为白点,且father[x] 为黑点

2:x 白点,father[x] 白点

 

f[x][0] = sum{ min(f[y][0],f[y][1] ) +1;   

f[x][1]=  sum{ f[y][2] }               // x为白点,且father[x] 为黑点

 

f[x][2] 需要枚举一个子节点 W 作为黑点,然后其他的的点为白,但这样做 复杂度O(n^2) 

利用算出来的 f[x][1]  ,

        f[x][2]= min( f[x][1] - f[y][2] +f[y][0] }

 

 

#include <iostream>
#include <vector>
#include <cstring>
using namespace std ; 
 const int N=2e4;
 #define int long long
 
 vector<int>g[N];
 int n,f[N][3];
 
 void dp(int x,int fa){
 	f[x][0]=1;f[x][2]=1<<30;
 	
 	for(auto y:g[x]){
 		if(y==fa) continue;
 		dp(y,x);
 		f[x][0]+=min(f[y][0],f[y][1]);
 		f[x][1]+=f[y][2];
	 }
	 for(auto y:g[x]){
 		if(y==fa) continue;
 		f[x][2]=min(f[x][2],f[x][1]-f[y][2]+f[y][0]);
 	 }
 }
 
 signed main(){
 	int i,x,y;

 	while(cin>>n){
	 	memset(f,0,sizeof f);
	 	for(i=1;i<=n;i++) g[i].clear();
	 	
	 	for(i=1;i<n;i++) 
		  cin>>x>>y,g[x].push_back(y),g[y].push_back(x);;
	 	cin>>x;
	 	dp(1,0);
	 	cout<<min(f[1][0],f[1][2])<<'\n';
	 	if(x==-1) break;
 	}
 } 
 
 
 

 

 
 
 

 

posted on 2022-10-18 16:36  towboat  阅读(18)  评论(0)    收藏  举报