BZOJ1304 CQOI2009叶子的染色(树形dp)
令f[i]表示i子树内最少染色次数,加上012状态分别表示该子树内叶节点已均被满足、存在黑色叶节点未被满足、存在白色叶节点未被满足,考虑i节点涂色情况即可转移。事实上贪心也可以。
#include<iostream> #include<cstdio> #include<cmath> #include<cstdlib> #include<cstring> #include<algorithm> using namespace std; int read() { int x=0,f=1;char c=getchar(); while (c<'0'||c>'9') {if (c=='-') f=-1;c=getchar();} while (c>='0'&&c<='9') x=(x<<1)+(x<<3)+(c^48),c=getchar(); return x*f; } #define N 100010 int n,m,f[N][3],c[N],p[N],t=0; struct data{int to,nxt; }edge[N<<1]; void addedge(int x,int y){t++;edge[t].to=y,edge[t].nxt=p[x],p[x]=t;} void dfs(int k,int from) { if (k<=m) f[k][0]=1,f[k][c[k]]=0,f[k][c[k]]=n; else { f[k][0]=f[k][1]=f[k][2]=0; for (int i=p[k];i;i=edge[i].nxt) if (edge[i].to!=from) { dfs(edge[i].to,k); f[k][0]+=f[edge[i].to][0]; f[k][1]+=min(f[edge[i].to][1],f[edge[i].to][0]); f[k][2]+=min(f[edge[i].to][2],f[edge[i].to][0]); } f[k][0]=min(f[k][0],min(f[k][1],f[k][2])+1); } } int main() { #ifndef ONLINE_JUDGE freopen("bzoj1304.in","r",stdin); freopen("bzoj1304.out","w",stdout); const char LL[]="%I64d\n"; #else const char LL[]="%lld\n"; #endif n=read(),m=read(); for (int i=1;i<=m;i++) c[i]=read()+1; for (int i=1;i<n;i++) { int x=read(),y=read(); addedge(x,y),addedge(y,x); } dfs(n,n); cout<<f[n][0]; return 0; }