【刷题记录】 HDU6228 Tree 树状DP+策略

目录

一. 问题描述

二. 题解代码


一. 问题描述

Problem Description

给一颗n个节点,n-1条边的无根树,现在有k种颜色,用这k种颜色给树节点来染色

定义Ei = {边| 所有连接用 i颜色 染色的点之间的边 }

”define Ei as the minimum subset of edges connecting all nodes coloured by i“

求所有Ei交集的最大元素数。

二. 题解代码

        直接理解Ei会很懵,Ei只是连接用颜色i染色的点之间的边,怎么会跟另一种颜色边产生交集?其实Ei是指,任意两个i染色点之间的路径上的所有边的集合,要不然哪来的交集?

        交集的边,肯定是所有k种颜色都经过的边,那么也就是说在这条边两侧都有k种颜色,才会经过。也就是这条边两侧都要有>=k个节点才能出现,所以这里就用到了树状dp来统计点一侧的点数x,另一侧n-x;

#include <iostream>
#include<bits/stdc++.h>
using namespace std;
const int maxn = 100000 + 7;
int n,k,head[maxn*2],tot,sum[maxn*2],ans;
struct Edge{
    int to,next;
}edge[maxn*2];
void addEdge(int a,int b){
   edge[tot].to = b;edge[tot].next = head[a];head[a] = tot++;
}
void init(){
    tot = 0;
    memset(head,-1,sizeof(head));
}
void DFS(int root,int fa){//统计树上节点
   sum[root] = 1;
   for(int i = head[root];~i;i = edge[i].next){
       int to = edge[i].to;
       if(to==fa)continue;
       DFS(to,root);
       sum[root]+=sum[to];
       if(sum[to]>=k&&n-sum[to]>=k)ans++;
   }
   return;
}
int main()
{
    int T;
    scanf("%d",&T);
    while(T--){
        init();
        scanf("%d%d",&n,&k);
        for(int i = 1;i<=n-1;i++){
            int a,b;
            scanf("%d%d",&a,&b);
            addEdge(a,b);
            addEdge(b,a);
        }
        ans = 0;
        DFS(1,0);
        printf("%d\n",ans);
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

阿阿阿安

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值