目录
一. 问题描述
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;
}