bzoj 3197

题解:

先找到中信

然后dp

代码:

#include<bits/stdc++.h>
using namespace std;
const int N=1005;
int n,mx,go,bx,by,rot,x,y,g[N][20],a[N],b[N],s[N],c[N],f[N]; 
void dfs(int x,int fa,int dep) 
{
    s[++s[0]]=x;
    if (dep>mx)
     {
        mx=dep;
        go=x;
        memcpy(c,s,sizeof s);
     }
    for (int i=1;i<=g[x][0];i++) 
     if (g[x][i]!=fa) dfs(g[x][i],x,dep+1);
    s[0]--;
}
void build(int x,int fa) 
{
    int t[20];
    t[0]=0;
    for (int i=1;i<=g[x][0];i++)
     if (g[x][i]!=fa&&!(x==bx&&g[x][i]==by||x==by&&g[x][i]==bx))
      t[++t[0]]=g[x][i];
    memcpy(g[x],t,sizeof t);
    for (int i=1;i<=g[x][0];i++) build(g[x][i],x);
}
int dp(int x,int y) 
{
    int w[20][20];
    if (g[x][0]!=g[y][0]) return (~0U>>1);
    for (int i=1;i<=g[x][0];i++)
     for (int j=1;j<=g[y][0];j++)w[i][j]=dp(g[x][i],g[y][j]);
    for (int i=0;i<1<<g[x][0];i++)f[i]=(~0U>>1);
    f[(1<<g[x][0])-1]=0;
    for (int i=(1<<g[x][0])-1;i;i--)
     if (f[i]<(~0U>>1))
      {
        int cnt=g[x][0];
        for (int j=0;j<g[x][0];j++)
         if (i&(1<<j)) cnt--;
        for (int j=0;j<g[x][0];j++)
         if (i&(1<<j))f[i^(1<<j)]=min(f[i^(1<<j)],f[i]+w[cnt+1][j+1]);
      }
    return f[0]+(a[x]!=b[y]);
}
int main() 
{
    scanf("%d",&n);
    for (int i=1;i<n;i++)
     {
        scanf("%d%d",&x,&y);
        g[x][++g[x][0]]=y;
        g[y][++g[y][0]]=x;
     }
    for (int i=1;i<=n;i++) scanf("%d",&a[i]);
    for (int i=1;i<=n;i++) scanf("%d",&b[i]);
    dfs(1,0,0);
    dfs(go,mx=0,0);
    if (c[0]&1) rot=c[1+c[0]>>1]; 
    else
     {
        rot=n+1;
        bx=g[rot][++g[rot][0]]=c[c[0]>>1];
        by=g[rot][++g[rot][0]]=c[(c[0]>>1)+1];
     }
    build(rot,0);
    printf("%d",dp(rot,rot));
    return 0;
}
原文地址:https://www.cnblogs.com/xuanyiming/p/8322085.html