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
0
1
0
1 4
2 5
4 5
3 5
Sample Output
2
HINT
M<=10000
N<=5021
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
struct node
{
int x,y,next;
}a[21000];int len,last[11000];
void ins(int x,int y)
{
len++;
a[len].x=x;a[len].y=y;
a[len].next=last[x];last[x]=len;
}
int m,n;
int c[11000];
int f[11000][2];//f[i][j]表示x染j色,以x为根的子树要合法最少要染的点数
void dfs(int x,int fa)
{
if(x<=n)//来到了c[]的叶子节点了
{
f[x][c[x]]=0;
//因为已经确定了颜色c[x],所以去掉另外的颜色
if(c[x]==1) f[x][0]=999999999;
else f[x][1]=999999999;
return ;
}
for(int k=last[x];k;k=a[k].next)
{
int y=a[k].y;
if(y!=fa)
{
dfs(y,x);
//爸爸和儿子颜色不同肯定要+1的
f[x][0]+=min(f[y][1]+1,f[y][0]);
f[x][1]+=min(f[y][0]+1,f[y][1]);
}
}
}
int main()
{
len=0;memset(last,0,sizeof(last));
int a,b;
scanf("%d%d",&m,&n);
for(int i=1;i<=n;i++) scanf("%d",&c[i]);
for(int i=1;i<m;i++)
{
scanf("%d%d",&a,&b);
ins(a,b);ins(b,a);
}
memset(f,0,sizeof(f));
dfs(m,0);
printf("%d\n",min(f[m][0],f[m][1])+1);//加上染爸爸这个点的
return 0;
}