[CQOI2009]叶子的染色

https://www.zybuluo.com/ysner/note/1307594

题面

戳我

解析

一开始脑抽了,状态转移时默认直接在子结点染色。。。
其实这道题还是很简单的。
\(dp[0/1/2][u]\)表示子树内的叶子结点还需要颜色\(0/1\),或都不需要颜色。
然后直接转移就对了。

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<algorithm>
#define ll long long
#define re register
#define il inline
#define fp(i,a,b) for(re int i=a;i<=b;i++)
#define fq(i,a,b) for(re int i=a;i>=b;i--)
using namespace std;
const int N=1e4+100;
int n,m,h[N],cnt,w[N],dp[3][N];
struct Edge{int to,nxt;}e[N<<1];
il void add(re int u,re int v){e[++cnt]=(Edge){v,h[u]};h[u]=cnt;}
il ll gi()
{
  re ll x=0,t=1;
  re char ch=getchar();
  while(ch!='-'&&(ch<'0'||ch>'9')) ch=getchar();
  if(ch=='-') t=-1,ch=getchar();
  while(ch>='0'&&ch<='9') x=x*10+ch-48,ch=getchar();
  return x*t;
}
il void dfs(re int u,re int fa)
{
  if(u<=m) dp[2][u]=1,dp[!w[u]][u]=1e5;
  for(re int i=h[u];i+1;i=e[i].nxt)
    {
      re int v=e[i].to;
      if(v==fa) continue;
      dfs(v,u);
      dp[0][u]+=min(dp[0][v],dp[2][v]);
      dp[1][u]+=min(dp[1][v],dp[2][v]);
      dp[2][u]+=dp[2][v];
    }
  dp[2][u]=min(dp[2][u],min(dp[1][u],dp[0][u])+1);
}
int main()
{
  memset(h,-1,sizeof(h));
  n=gi();m=gi();
  fp(i,1,m) w[i]=gi();
  fp(i,1,n-1)
    {
      re int u=gi(),v=gi();
      add(u,v);add(v,u);
    }
  dfs(n,0);
  printf("%d\n",dp[2][n]);
  return 0;
}                                      
posted @ 2018-10-11 23:02  小蒟蒻ysn  阅读(208)  评论(0编辑  收藏  举报