随笔 - 531  文章 - 0  评论 - 3  阅读 - 10215 

 

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

 

 

白点只和一个黑点相连,所以对于节点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] }

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#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   towboat  阅读(12)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示