题意:
给出一棵树,每一个节点染成某种颜色需要花费 a a a, 每个节点和它直接相连的节点需要染成的颜色互不相同,问染完整棵树的最小花费。
思路:
由于颜色只有3种,画一画图会发现,如果每个节点的度数超过2,那么一定无解。 也就是说给出的树是一条树链。
那么颜色只有3种,一共有6种染色状态,先dfs出树链,然后直接暴力枚举所有状态、
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<stdio.h>
#include<string.h>
#include<queue>
#include<cmath>
#include<map>
#include<set>
#include<vector>
using namespace std;
#define inf 0x3f3f3f3f
#define lson l,mid,rt<<1
#define rson mid+1,r,rt<<1|1
#define mem(a,b) memset(a,b,sizeof(a));
#define lowbit(x) x&-x;
#define debugint(name,x) printf("%s: %d\n",name,x);
#define debugstring(name,x) printf("%s: %s\n",name,x);
typedef long long ll;
typedef unsigned long long ull;
const double eps = 1e-6;
const int maxn = 1e5+5;
const int mod = 1e9+7;
inline int read()
{
int x=0,f=1;char ch=getchar();
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;
int a[maxn][4];
vector<int>v[maxn];
int st[6][3]={
{0,1,2},
{0,2,1},
{1,0,2},
{1,2,0},
{2,0,1},
{2,1,0}
};
int in[maxn];
int col[maxn];
int path[maxn],tol = 0;
int ansp[maxn];
ll cnt;
void dfs(int u,int fa){
path[tol++] = u;
for(auto vv:v[u]){
if(vv == fa) continue;
dfs(vv,u);
}
}
int main() {
scanf("%d",&n);
for(int i = 0; i < 3; i++){
for(int j = 1; j <= n; j++){
scanf("%d",&a[j][i]);
}
}
int ok = 1;
for(int i = 1; i < n; i++){
int x,y;
scanf("%d%d",&x,&y);
in[x]++;
in[y]++;
if(in[x] > 2 || in[y] > 2){
ok = 0;
}
v[x].push_back(y);
v[y].push_back(x);
}
ll ans = 1e18;
int rt1, rt2;
if(!ok) puts("-1");
else{
int rt;
for(int i = 1; i <= n; i++){
if(in[i] == 1) {
rt = i;
break;
}
}
dfs(rt,0);
int res = 0;
for(int i = 0; i < 6; i++){
res = 0, cnt = 0;
for(int j = 0; j < 3; j++){
col[j] = st[i][j];
cnt += a[path[j]][st[i][j]];
}
for(int j = 3; j < tol; j++){
col[j] = col[j%3];
cnt += a[path[j]][col[j%3]];
}
if(ans > cnt){
ans = cnt;
for(int j = 0; j < tol; j++)
ansp[path[j]] = col[j];
}
}
printf("%lld\n",ans);
for(int i = 1; i <= n; i++)
printf("%d ",ansp[i]+1);
}
}