树形DP 入门题吧(现在怎么是蓝色标签搞不懂);

注意是看见每一条边而不是每一个点(因为这里错了好几次);

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=3010;
int pre[maxn],last[maxn],other[maxn],l;

void add(int x,int y)
{
    l++;
    pre[l]=last[x];
    last[x]=l;
    other[l]=y;
}

int n;
int f[maxn][2];

void dfs(int x,int fa)
{
    f[x][1]=1;f[x][0]=0;
    for(int p=last[x];p;p=pre[p])
    {
        int v=other[p];
        if(v==fa) continue;
        dfs(v,x);
        f[x][1]+=min(f[v][0],f[v][1]);
        f[x][0]+=f[v][1];
    }
}

int main()
{
    scanf("%d",&n);
    for(int i=1;i<=n;i++)
    {
        int x,k,y; 
        scanf("%d%d",&x,&k);
        x++;
        for(int j=1;j<=k;j++) 
        {
            scanf("%d",&y);
            y++;
            add(x,y);
            add(y,x);
        }
    }
    dfs(1,0);
    printf("%d",min(f[1][1],f[1][0]));
    return 0;
}
View Code

相关文章:

  • 2021-11-11
  • 2022-12-23
  • 2021-07-05
  • 2022-01-26
  • 2021-11-29
  • 2021-10-31
  • 2021-05-31
  • 2022-12-23
猜你喜欢
  • 2021-08-07
  • 2022-12-23
  • 2021-05-23
  • 2022-12-23
  • 2021-12-31
  • 2022-01-11
  • 2021-10-08
相关资源
相似解决方案