Codeforces Round #592 (Div. 2) D. Paint the Tree(构造)
程序员文章站
2022-04-27 11:35:20
...
题目链接
题意:给定一棵树,要求你给每个节点涂色,要求连续的三个节点的颜色不能相同,每个节点涂三个颜色的花费分别是a【i】,b【i】,c【i】,问你满足要求的最小花费。
思路:很显然,画个图就知道能满足条件的只有链的情况,于是我们只要固定从根节点开始的前三个节点的颜色,那么整条链的颜色就都确定了。
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=1e5+5;
vector<int>g[maxn];
ll a[maxn],b[maxn],c[maxn],ans[7][maxn],minn=2e18,temp;
void dfs(int x,int fa,int a,int b,int c,int deep,int id)
{
if(deep%3==1) ans[id][x]=a;
else if(deep%3==2) ans[id][x]=b;
else if(deep%3==0) ans[id][x]=c;
for(int to:g[x])
{
if(to==fa) continue;
dfs(to,x,a,b,c,deep+1,id);
}
}
int main()
{
int k,n,x,y,root=1;
scanf("%d",&n);
for(int i=1;i<=n;++i) scanf("%lld",&a[i]);
for(int i=1;i<=n;++i) scanf("%lld",&b[i]);
for(int i=1;i<=n;++i) scanf("%lld",&c[i]);
for(int i=1;i<n;++i)
{
scanf("%d %d",&x,&y);
g[x].push_back(y);
g[y].push_back(x);
}
for(int i=1;i<=n;++i)
{
if(g[i].size()==1) root=i;
if(g[i].size()>2){
puts("-1");return 0;
}
}
dfs(root,0,1,2,3,1,1);dfs(root,0,1,3,2,1,2);dfs(root,0,2,1,3,1,3);dfs(root,0,2,3,1,1,4);dfs(root,0,3,2,1,1,5);dfs(root,0,3,1,2,1,6);
for(int i=1;i<=6;++i)
{
temp=0;
for(int j=1;j<=n;++j)
{
if(ans[i][j]==1) temp+=a[j];
else if(ans[i][j]==2) temp+=b[j];
else temp+=c[j];
}
if(temp<minn) minn=temp,k=i;
}
printf("%lld\n",minn);
for(int i=1;i<=n;++i) printf("%d ",ans[k][i]);
}
上一篇: 【树】B038_LC_根到叶路径上的不足节点(后序遍历)
下一篇: 分裂二叉树的最大乘积-力扣周赛题
推荐阅读
-
Codeforces Round #482 (Div. 2) D. Kuro and GCD and XOR and SUM(数学+01字典树)(好题)
-
Codeforces Round #FF (Div. 2) D. DZY Loves Modification 贪心+优先队列_html/css_WEB-ITnose
-
Educational Codeforces Round 97 (Rated for Div. 2) D. Minimal Height Tree
-
Codeforces Round #665 (Div. 2) D. Maximum Distributed Tree(dfs)
-
构造思维+树形结构 Codeforces Round #612 (Div. 2) D题 Numbers on Tree
-
Codeforces Round #670 (Div. 2) E. Deleting Numbers(交互,素数构造)
-
Codeforces Round #619 (Div. 2) D. Time to Run
-
Codeforces Round #583 (Div. 1 + Div. 2,) D. Treasure Island(dfs+思维)
-
Codeforces Round #533 (Div. 2) D. Kilani and the Game(bfs+模拟)
-
Codeforces Round #643 (Div. 2) D. Game With Array