1304: [CQOI2009]叶子的染色
Description
给一棵m个结点的无根树,你可以选择一个度数大于1的结点作为根,然后给一些结点(根、内部结点和叶子均可)着以黑色或白色。你的着色方案应该保证根结点到每个叶子的简单路径上都至少包含一个有色结点(哪怕是这个叶子本身)。 对于每个叶结点u,定义c[u]为从根结点从U的简单路径上最后一个有色结点的颜色。给出每个c[u]的值,设计着色方案,使得着色结点的个数尽量少。
Input
第一行包含两个正整数m, n,其中n是叶子的个数,m是结点总数。结点编号为1,2,…,m,其中编号1,2,… ,n是叶子。以下n行每行一个0或1的整数(0表示黑色,1表示白色),依次为c[1],c[2],…,c[n]。以下m-1行每行两个整数a,b(1<=a < b <= m),表示结点a和b 有边相连。
Output
仅一个数,即着色结点数的最小值。
Sample Input
5 3
0
1
0
1 4
2 5
4 5
3 5
Sample Output
2
HINT
M<=10000
N<=5021
题解
这道题不难发现是一道树形DP,因为题目要求到达叶子节点的简单路径上最后染色的节点满足要求。我们只需要从下往上来做是没有后效性的,对于每个非叶子节点,我们统计它的儿子节点所需要染黑色的个数和白色的节点个数还有染黑染白无所谓的(仅仅是直接连接的节点)。将这个节点的儿子节点最少所需要染色的个数都加起来再减去当前节点染色后,儿子节点能少染多少的个数,就是当前节点所需要最少染得个数。
至于当前节点要染什么颜色,可以采用贪心,儿子节点染白色的多就染白色,黑色多就染黑色,一样多的话就标记为染黑染白无所谓的。
代码:
#include<iostream>
#include<vector>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define ll long long
using namespace std;
#define N 10005
inline int read(){
char ch=getchar(); int x=0,f=1;
while (ch<'0'||ch>'9') { if (ch=='-') f=-1; ch=getchar(); }
while (ch>='0'&&ch<='9') { x=x*10+ch-'0'; ch=getchar(); }
return x*f;
}
int n,m;
int color[N];
int w[N],b[N],q[N];
int f[N];
int nxt[N*2],to[N*2],head[N],cnt;
void add_edge(int u,int v){
to[++cnt] = v; nxt[cnt] = head[u]; head[u] = cnt;
to[++cnt] = u; nxt[cnt] = head[v]; head[v] = cnt;
}
void dfs1(int x,int fa){
if(x <= m){
if(color[x] == 1)
w[x] = 1;
else b[x] = 1;
return;
}
for(int i = head[x];i;i = nxt[i])
if(to[i] != fa){
dfs1(to[i],x);
if(color[to[i]] == -1) q[x]++;
else if(color[to[i]] == 1) w[x]++;
else b[x]++;
f[x] += f[to[i]];
}
if(b[x] > w[x]){
color[x] = 0;
f[x] -= b[x]+q[x]-1;
}
else if(b[x] < w[x]){
color[x] = 1;
f[x] -= w[x]+q[x]-1;
}
else{
color[x] = -1;
f[x] -= w[x]+q[x]-1;
}
}
int main(){
n = read(); m = read();
for(int i = 1;i <= m;++i){
f[i] = 1;
color[i] = read();
}
for(int i = 1;i < n;++i){
int a = read(),b = read();
add_edge(a,b);
}
memset(b,0,sizeof b);
memset(w,0,sizeof w);
dfs1(m+1,0);
printf("%d\n",f[m+1]);
return 0;
}