You are given a tree consisting of n vertices. A tree is an undirected connected acyclic graph.
Example of a tree.
You have to paint each vertex into one of three colors. For each vertex, you know the cost of painting it in every color.
You have to paint the vertices so that any path consisting of exactly three distinct vertices does not contain any vertices with equal colors. In other words, let's consider all triples (x, y, z) such that x ≠ y, y ≠ z, x ≠ z, x is connected by an edge with y, and y is connected by an edge with z. The colours of x, y and z should be pairwise distinct. Let's call a painting which meets this condition good.
You have to calculate the minimum cost of a good painting and find one of the optimal paintings. If there is no good painting, report about it.
Input
The first line contains one integer n (3 ≤ n ≤ 100 000) — the number of vertices.
The second line contains a sequence of integers c_{1, 1}, c_{1, 2}, ..., c_{1, n} (1 ≤ c_{1, i} ≤ 10^{9}), where c_{1, i} is the cost of painting the i-th vertex into the first color.
The third line contains a sequence of integers c_{2, 1}, c_{2, 2}, ..., c_{2, n} (1 ≤ c_{2, i} ≤ 10^{9}), where c_{2, i} is the cost of painting the i-th vertex into the second color.
The fourth line contains a sequence of integers c_{3, 1}, c_{3, 2}, ..., c_{3, n} (1 ≤ c_{3, i} ≤ 10^{9}), where c_{3, i} is the cost of painting the i-th vertex into the third color.
Then (n - 1) lines follow, each containing two integers u_j and v_j (1 ≤ u_j, v_j ≤ n, u_j ≠ v_j) — the numbers of vertices connected by the j-th undirected edge. It is guaranteed that these edges denote a tree.
Output
If there is no good painting, print -1.
Otherwise, print the minimum cost of a good painting in the first line. In the second line print n integers b_1, b_2, ..., b_n (1 ≤ b_i ≤ 3), where the i-th integer should denote the color of the i-th vertex. If there are multiple good paintings with minimum cost, print any of them.
Examples
Input
3
3 2 3
4 3 2
3 1 3
1 2
2 3
Output
6
1 3 2
Input
5
3 4 2 1 2
4 2 1 5 4
5 3 2 1 1
1 2
3 2
4 3
5 3
Output
-1
Input
5
3 4 2 1 2
4 2 1 5 4
5 3 2 1 1
1 2
3 2
4 3
5 4
Output
9
1 3 2 1 3
Note
All vertices should be painted in different colors in the first example. The optimal way to do it is to paint the first vertex into color 1, the second vertex — into color 3, and the third vertex — into color 2. The cost of this painting is 3 + 2 + 1 = 6.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
We need to parse problem: tree, each vertex must be colored with one of three colors. The condition: For any path of length 2 (i.e., three vertices x-y-z where edges x-y and y-z) all three colors must be distinct. Equivalent: For any vertex, its neighbors cannot have the same color as it? Actually, consider a vertex y and its two neighbors x and z (maybe more). The condition says that for any two distinct neighbors x and z of y, we require that x,y,z all have distinct colors. However, the problem statement: "any path consisting of exactly three distinct vertices does not contain any vertices with equal colors." Path of three vertices (x,y,z) where edges (x,y) and (y,z). It does not require x and z are distinct? It says x ≠ y, y ≠ z, x ≠ z, so they are all distinct. So for any edge pair (x-y) and (y-z) with x≠z, we need colors all different. So this implies: For any vertex y, and any two distinct neighbors x and z, colors(x) != colors(y) and colors(x) != colors(z) and colors(y) != colors(z). But note it's automatically that colors(x) != colors(y) and colors(z) != colors(y) if we consider path x-y and separately path z-y? Actually the condition includes only length-2 paths. It does not directly forbid a neighbor having same color as y because that would create a path where x and y have same color? Let's check: Suppose neighbor x of y has same color as y. Then consider path x-y-z for any other neighbor z of y. Then colors(x)=colors(y) but x≠y, so condition violated because x and y have equal colors. So indeed, any vertex cannot share color with any of its neighbors. So the coloring must be a proper coloring (no adjacent vertices same color). Additionally, for any vertex with degree ≥2, the colors of its neighbors must be all distinct from each other? Actually condition also requires for path x-y-z that colors(x) ≠ colors(z). That means for any two distinct neighbors x and z of y, they must have different colors. So the neighbors of a vertex must all have pairwise distinct colors. Since there are only 3 colors, that implies the degree of any vertex cannot exceed 2? Let's see: If a vertex y has degree d, then all neighbors must have distinct colors. With only 3 colors, the maximum d is 3 (if all three colors used among neighbors). But also note that y itself must have a color distinct from all neighbors, so y's color must be different from all neighbor colors. So overall, if a vertex y has degree d, then we have d neighbor colors all distinct, and y's color must be different from each of them. That's d+1 distinct colors needed. Since only 3 colors available, d+1 ≤ 3 => d ≤ 2. So every vertex must have degree ≤ 2. This is a necessary condition for a good painting to exist. Because if any vertex has degree 3 or more, we would need at least 4 distinct colors.
Thus the tree must be a path (or possibly a cycle? But it's a tree, so no cycles. With max degree 2, the tree is a simple path. So the tree must be a path graph (i.e., all vertices degree ≤2). So if any vertex has degree >2, output -1. Indeed, second example gives -1 presumably because there is a vertex of degree 3? Let's check: In input 2: n=5, edges: 1-2, 3-2, 4-3, 5-3. Vertex 2 connects to 1 and 3 (degree 2). Vertex 3 connects to 2,4,5 (degree 3). So degree 3 => -1. So condition matches.
Thus we only need to solve for a path (tree which is a path). However, careful: The tree could be like a 'line' but also a single vertex? n≥3 so path length at least 3. So we have a path of n vertices.
Now we need to assign colors 1,2,3 to each vertex along the path such that for any consecutive triple (i, i+1, i+2) the colors are all distinct. Actually the condition is for any path of exactly three distinct vertices, which in a path graph includes all consecutive triples. But also consider non-consecutive triples? For example, vertices 1-2-4? Not a path because no edge 2-4. So only contiguous triples. So condition reduces to: For any three consecutive vertices i, i+1, i+2, they must all be distinct colors. Additionally, adjacent vertices cannot have same color, but that's already implied.
Thus we have a linear constraint: colors on a path of length n (vertices 1..n along the path) with colors 1,2,3, such that for any i from 1 to n-2, color[i], color[i+1], color[i+2] are all distinct. This is a known problem: essentially we need a proper 3-coloring of a path with the extra condition that no three consecutive are all different? Actually they must be all distinct, so each triple must contain all three colors. Since only three colors, that means that the set of colors of any three consecutive vertices is exactly {1,2,3}. So the coloring must be a permutation of the three colors repeated in some pattern? Let's think: For positions 1,2,3: they are all distinct. For positions 2,3,4: they must also be all distinct. Given that 2 and 3 are distinct, for 4 we need a color different from both 2 and 3. Since there are only three colors, the only color left for 4 is the color of vertex 1. So color[4] = color[1]. Similarly, for triple 3,4,5: colors 3 and 4 are distinct (since 3 distinct from 1? Actually 3 and 4: color[3] is some, color[4]=color[1]. They are distinct because triple 1,2,3 all distinct implies color[1] ≠ color[3]). So for 5, it must be the color different from color[3] and color[4]. Since colors are from {1,2,3}, and we have two distinct colors, the third is uniquely determined, and note that color[5] must equal color[2]? Let's see: The pattern emerges: The colors must alternate in a cycle of length 3. Indeed, along the path, if we start with colors (c1, c2, c3) being a permutation of (1,2,3), then we are forced: c4 = c1, c5 = c2, c6 = c3, c7 = c1, etc. So the coloring is periodic with period 3. And this automatically satisfies the condition for all triples (since any three consecutive are shift of the initial triple). So there are exactly 6 possible colorings (all permutations of (1,2,3) for the first three vertices, and then the rest determined). However, we must also check that the condition holds for triples that may be not exactly starting at index 1? But by construction it does.
But wait, is there any other possible coloring? Suppose we assign colors that don't follow this periodic pattern but still satisfy all triples? Let's test small n. For n=3, any permutation works (6). For n=4, we have c1,c2,c3 distinct, and for triple (2,3,4) all distinct, so c4 must be different from c2 and c3. Since c2 ≠ c3, the only color left is the one not among {c2,c3}, which is c1. So c4 = c1. So indeed forced. For n=5, similarly c5 must be the one not among {c3,c4}= {c3,c1} (since c4=c1). The missing color is c2. So forced. So yes, only periodic pattern. So there are exactly 6 possible assignments for a given ordering of vertices along the path.
But careful: The tree is a path, but the vertices are not necessarily labeled in order along the path. We need to extract the path order. Since tree is just edges, we must find an endpoint (degree 1) and then traverse to get the sequence of vertices. Then we have two possible directions (start from either endpoint). However, the coloring pattern along the path can be one of 6 permutations for the first three vertices, but note that the path direction matters because the permutation is defined relative to order. However, the 6 patterns are essentially all cyclic rotations? Actually if we reverse the order, the pattern becomes reversed? But since the condition is symmetric, any coloring corresponds to some ordering. But we can simply compute the minimum cost over the 6 possibilities for the given path order (with a fixed direction). But careful: The 6 patterns correspond to the 3! permutations of colors for the first three positions. However, the pattern is determined by the first three vertices. But if we reverse the path order, we might get a different mapping of colors to vertices because the sequence of vertices is reversed. But the set of colorings is the same set; enumerating patterns for a fixed order (like from endpoint A to B) covers all possible colorings? Let's check: Suppose we fix an order v1, v2, ..., vn along the path (starting from one endpoint). Any valid coloring must be of form: for some permutation (p1, p2, p3) of (1,2,3), color[vi] = p_{(i-1)%3 + 1}. So indeed, that gives 6 distinct assignments for that order. However, what if we consider the other direction? That would correspond to a different assignment? Actually, if we reverse the order, the same coloring would correspond to a different permutation of colors for the first three vertices of the reversed order. But as we are enumerating all 6 permutations for the fixed order, we are covering all possible colorings because any coloring is periodic, and for that order, it will match one of the 6 patterns. But is it possible that a coloring doesn't follow that pattern for the given order? We argued it's forced, so yes. So enumeration over 6 permutations for that order suffices.
But we must be careful: The pattern is with period 3, but the starting index could be offset? Actually the pattern is: color[i] = color[i+3]. So the sequence is periodic with period 3. The pattern is determined by colors at positions 1,2,3. So 6 possibilities. Good.
Thus the problem reduces to: Given a path of n vertices (v1,...,vn) (order matters), and costs for each vertex for each color (1,2,3). For each of the 6 assignments (permutations of colors for the residues mod 3), compute total cost. Then output the minimal cost and the assignment.
But is there any nuance: The tree might have max degree 2 but might have only two vertices? But n≥3 so okay. Also, if the path has endpoints (degree 1), correct.
Thus algorithm: read n and costs arrays (size n for each color). Then read edges. Build adjacency list. Check for each vertex if degree > 2; if any, output -1. Also, if n==1? not allowed. Also if there is a vertex degree 0? tree connected so no isolated.
But wait: What about a tree that is a path but with n vertices? all degrees ≤2, but also must have exactly two vertices with degree 1 (the endpoints) and the rest degree 2. If any vertex has degree 0, not connected; but tree connected ensures at least 1 neighbor. So okay.
But we also must ensure tree is indeed a path: all degrees ≤2. That's necessary and sufficient for a tree? Actually a tree with all vertices degree ≤2 is either a path or a single vertex? A tree that is a line has endpoints degree 1, internal degree 2. Could there be a tree with a vertex degree 0? only if n=1. So for n≥3, it's a path. So condition is fine.
But wait: Could there be a tree with all degrees ≤2 but not a simple path? A tree with n vertices and max degree 2 must be a path (or a cycle if it had a cycle, but it's a tree, so acyclic). So it's a path. Good.
Now after confirming, we need to construct the path order. Find an endpoint (degree 1). Then do a DFS or simple traversal to list vertices in order from that endpoint. Since each vertex has at most 2 neighbors, we can start from endpoint and follow: set prev = -1, curr = endpoint, then repeatedly add curr to list, then for each neighbor of curr, if neighbor != prev, set prev=curr, curr=neighbor. Loop until no neighbor (i.e., reached other endpoint). This yields order v1,...,vn.
Now we have cost arrays: let's store cost[color][vertex] (0-indexed). For each permutation perm of [1,2,3] (or 0,1,2) we assign colors to vertices based on index i (1-indexed in path order): color_idx = (i-1) % 3, the color is perm[color_idx]. Compute total cost = sum over i: cost[ perm[(i-1)%3] ][ v_i ]. Keep track of min and which perm gives min.
Then output min cost and assignment: for each vertex (original numbering) we need to assign its color according to the chosen permutation and its position in the path order. So we must map from vertex id to its index in the order (0..n-1). Then assign color accordingly.
One nuance: Are there any other constraints? The condition says any path of exactly three distinct vertices does not contain any vertices with equal colors. In a path graph, any three vertices that are not consecutive may not form a path; only consecutive ones. So our deduction stands.
But wait: Consider a path of length 2 (three vertices) but if there is a vertex with degree 2 but only two neighbors, triple x-y-z where x and z are both neighbors of y; that's covered. There's no other triples.
Thus solution is straightforward.
But there is also possibility of the tree being a path but having two possible orientations. However, we fixed an orientation by picking one endpoint as start. But we enumerated permutations for that orientation. Does that cover all 6 possible colorings? Let's verify. For a given path order v1...vn, the valid colorings are exactly those that are periodic with period 3. There are 6 such assignments. So enumeration over 6 permutations covers all. However, if we had started from the other endpoint, the order would be reversed. The set of assignments for the reversed order is the same set? Actually if we reverse the order, the periodic pattern might map to a different permutation. But since we cover all 6 permutations for a fixed order, we have covered all assignments. Because any assignment that is valid for the path corresponds to a periodic pattern with some permutation for the order we chose. That is true: given a coloring, define v1...vn order from endpoint A to B. The colors at positions 1,2,3 are some permutation. So it's one of the 6. So enumeration over 6 for that order yields exactly that coloring. So orientation doesn't matter.
Thus solution seems simple.
But we must check edge case: n=3. Then we have 6 permutations. That's fine.
Now complexity: O(n) after building order and O(6*n) to compute costs; O(n) memory.
Now produce output: if no good painting (i.e., degree > 2) -> -1.
Now test examples.
Example 1:
n=3, costs:
c1: 3 2 3
c2: 4 3 2
c3: 3 1 3
Edges: 1-2,2-3. Path: 1-2-3. Compute total for each permutation. Let's compute: we have costs per vertex:
v1=1: costs: col1=3, col2=4, col3=3
v2=2: col1=2, col2=3, col3=1
v3=3: col1=3, col2=2, col3=3
Permutation (1,2,3): cost: v1 col1=3, v2 col2=3, v3 col3=3 => total 9? Actually 3+3+3=9. But expected min is 6. Let's list all 6:
Example 3:
n=5, edges: 1-2,3-2,4-3,5-4? Wait input:
5
3 4 2 1 2
4 2 1 5 4
5 3 2 1 1
1 2
3 2
4 3
5 3
That's example 2? Actually example 2 is output -1. That tree has vertex 3 degree 3. Example 3: edges:
1 2
3 2
4 3
5 4 (from note, but check input: The last example Input:
5
3 4 2 1 2
4 2 1 5 4
5 3 2 1 1
1 2
3 2
4 3
5 3? That's what is written? Wait the third example in statement says:
Input
5
3 4 2 1 2
4 2 1 5 4
5 3 2 1 1
1 2
3 2
4 3
5 4
Output
9
1 3 2 1 3
So the edges are: 1-2, 3-2, 4-3, 5-4. That's a path? Let's check degrees: Vertex 2: edges to 1 and 3 => degree 2. Vertex 3: edges to 2 and 4 => degree 2. Vertex 4: edges to 3 and 5 => degree 2. Vertex 1: degree 1, vertex 5: degree 1. So it's a path: order can be 1-2-3-4-5 or reversed. So it's a valid path. Now we compute minimal cost. According to output, min cost 9, with colors 1 3 2 1 3. That corresponds to permutation (1,3,2) for positions 1,2,3? Let's see: positions: 1->1, 2->3, 3->2, then 4->1, 5->3. So indeed pattern (1,3,2) repeated. Let's compute cost:
Costs:
Vertex 1: c1=3, c2=4, c3=5? Actually input: line1: "3 4 2 1 2" for color1. line2: "4 2 1 5 4" for color2. line3: "5 3 2 1 1" for color3.
So for vertex 1: col1=3, col2=4, col3=5.
Vertex2: col1=4, col2=2, col3=3.
Vertex3: col1=2, col2=1, col3=2.
Vertex4: col1=1, col2=5, col3=1.
Vertex5: col1=2, col2=4, col3=1.
Now coloring: v1=1 cost3, v2=3 cost3, v3=2 cost1, v4=1 cost1, v5=3 cost1. Sum = 3+3+1+1+1=9. Yes.
Now enumeration over 6 permutations would find that.
Thus the solution works.
Now implement.
Implementation steps:
Read n.
Read three arrays of size n: cost[0][i], cost[1][i], cost[2][i] where indices 0,1,2 correspond to colors 1,2,3.
Build adjacency list (vector<vector> adj(n)).
For each edge, add both ends, check degree counts; after reading all edges, check if any vertex has degree > 2. If yes, print -1 and exit.
Also if n == 1? not allowed, but okay.
Actually also ensure there are exactly two vertices of degree 1? For a path, yes, but we already check degree <=2. However, for a tree to be a path, it must also be connected. Since we have tree, it's connected. But if all degrees <=2, and n>2, it must have at least two degree1. But there could be case where all vertices have degree <=2 but the tree is not a path? A tree with max degree 2 can only be a path. So it's fine. However, if there is a vertex degree 0 (not possible). So okay.
Find a vertex with degree 1 (endpoint). If all degrees are <=2 but no degree1? That would be a cycle? Not possible in tree (acyclic) for n>=2, there must be at least two leaves. Actually a tree with n>=2 always has at least two leaves (degree 1). So there will be. But to be safe, if none found, maybe graph is something else; but given it's a tree, we can just pick a vertex with degree >0 and start DFS from it, but it's easier to find leaf: for i in 0..n-1 if adj[i].size() == 1: start = i; break.
Traverse path order:
vector order;
int prev = -1;
int curr = start;
while (true) {
order.push_back(curr);
int next = -1;
for (int nb : adj[curr]) {
if (nb != prev) {
next = nb;
break;
}
}
if (next == -1) break;
prev = curr;
curr = next;
}
This yields order list of vertices indices (0-based).
Ensure order.size() == n; if not, something wrong? But should be.
Precompute an array pos_of_vertex[vertex] = index in order (0..n-1) for later assignment.
Define the 6 permutations as vectors of length 3: e.g., (0,1,2), (0,2,1), (1,0,2), (1,2,0), (2,0,1), (2,1,0). For each perm, compute total cost: total = 0; for i from 0 to n-1: color = perm[i % 3]; total += cost[color][ order[i] ];
Keep track of min total and best_perm.
After loop, output min total.
For each vertex v (0..n-1), compute its index in order: idx = pos[v]; color = best_perm[idx % 3] + 1 (since colors numbered 1..3). Output these colors.
Edge Cases:
n=3: works.
n large up to 100k, costs up to 1e9; total sum could be up to 1e14, so use long long (64-bit). Use int64_t.
Complexities: O(n).
But wait: The condition about any path of exactly three distinct vertices: In a tree that is a path, we considered only consecutive triples. However, what about triples like (v_i, v_{i+1}, v_{i+3})? That's not a path because v_{i+1} is not connected to v_{i+3} (only adjacent to i and i+2). So not considered. So fine.
Now verify second example: degree 3 => -1.
Thus solution is done.
But let's double-check the necessity of degree ≤2. Could there be a tree that is not a path but still satisfies the coloring condition? Suppose there is a vertex with degree 3, but maybe we can assign colors such that all neighbors have the same color? But condition requires for any two distinct neighbors x and z, colors(x), colors(y), colors(z) must be distinct. So neighbors must have distinct colors. So if degree is 3, then the three neighbors must all have distinct colors (since only 3 colors, they must be all three distinct). Also, vertex y's color must be distinct from all neighbors. So that would require 4 distinct colors. Impossible. So indeed degree ≤2 is necessary. So tree must be a path.
Thus algorithm stands.
But wait: Could there be a vertex with degree 2 but not in a simple path? Actually any tree with max degree 2 is a path. So yes.
Now, any other nuance: The problem asks for painting each vertex into one of three colors. The condition: "any path consisting of exactly three distinct vertices does not contain any vertices with equal colors." That means for any triple (x,y,z) with edges (x,y) and (y,z) and x≠z, the three colors must be distinct. This also includes cases where the path is not necessarily a subpath of the tree but maybe x and z could be the same if there is a multiple edge? No distinct vertices all. So fine.
Thus we are done.
Implementation details:
Reading input: n, then three lines each with n integers. We'll store costs as vector<vector> cost(3, vector(n)).
Edges: for i in 1..n-1, read u,v (1-indexed), convert to 0-index, add to adj.
After reading edges, check degrees: for each i if adj[i].size() > 2, output -1 and return.
Then find leaf: for i in 0..n-1 if adj[i].size() == 1: start = i; break. Since n≥3, leaf exists.
Traverse path: we can use iterative method.
Now note: There might be a case where the tree is a path but with n=2? But n≥3. So fine.
Now output: print min cost on first line. Second line: n integers colors (1-indexed). Ensure spaces.
Now test with given examples.
But I recall a Codeforces problem: "Three Colors" maybe? Actually this is CF Round #... I think it's #1199? Or #1012? Anyway.
Let's test manually with custom cases.
Case: n=4, path 1-2-3-4. costs arbitrary. Our enumeration over 6 permutations. Let's verify if any assignment that satisfies condition but not periodic? As argued earlier, for n=4 it's forced to have c4=c1. So only two possibilities for given c1,c2,c3? Actually permutations of first three determine all. So enumeration works.
Now, what about if the tree is a path but we choose the wrong start? The order from leaf will be either one direction or the other. But does enumeration over permutations of colors for indices from that order cover all possible colorings? Suppose a valid coloring exists. For that order (v1,...,vn), the coloring is periodic as discussed. So it will be represented by some permutation of colors for residues 0,1,2. So yes, we cover it. So orientation doesn't matter.
Thus solution is correct.
Now we need to be careful about using 64-bit integers. Use long long.
Complexities: O(n) time and O(n) memory.
Now one more thing: The problem constraints: n up to 100k, costs up to 1e9, so sum up to 1e14, fits in 64-bit.
Now just write code.
Potential pitfalls:
The tree could have vertices numbered arbitrarily; we must output colors for vertices in original order.
In path traversal, we must correctly get the entire path. Since it's a tree with max degree ≤2, the method works.
If there is no vertex with degree 1? In a tree with n>1, there are at least two leaves. But if n=1 (not allowed), so ok.
Edge case: n=2 (not allowed) but if it were, our condition? Actually n≥3.
Also note that if tree is a path but we have more than two endpoints? Actually in a path, exactly two endpoints (degree 1). So leaf start works.
Now let's double-check condition: "any path consisting of exactly three distinct vertices does not contain any vertices with equal colors." In a path graph, a path of three distinct vertices must be contiguous? Actually consider vertices 1-2-4? Not connected, so not a path. Only consecutive triples.
But what about a tree that is a path with a branch? But we already excluded branches because degree>2. So fine.
Now, potential alternative coloring: Could there be a coloring that is not periodic but still satisfies all triples? Let's test with n=5: Suppose we assign colors: 1,2,3,2,1. Check triples:
(1,2,3): 1,2,3 distinct OK.
(2,3,2): colors 2,3,2 -> 2 and 2 equal -> violation. So fails.
What about 1,2,3,1,2? Triples: (1,2,3) OK, (2,3,1) distinct, (3,1,2) distinct -> all distinct? Actually (3,1,2) all distinct. So this is periodic pattern (1,2,3,1,2) which is period 3. So it's forced.
For n=6: pattern (1,2,3,1,2,3) etc.
Thus indeed forced.
Thus solution done.
Now I'll implement.
But wait: Could there be a case where the tree is a path but the path order we extract is not consistent with the period? Actually any assignment that is valid will be periodic with period 3. So for a given order, the coloring is determined by first three. So enumeration of 6 possibilities is enough.
But note: The path order we get from a leaf may start from either leaf. But does that affect the mapping? Suppose a valid coloring exists. In one direction (from leaf A to leaf B), the pattern is some permutation p. If we reverse the direction, the pattern becomes some other permutation q. But both are among the 6 permutations for that direction? Actually, if we fix the direction from A to B, the pattern is p. So by enumerating over all 6 for that direction we will get p and compute its cost. So we don't need to also consider reverse direction; it's automatically covered because p is among the 6.
Thus fine.
Now, let's think about a degenerate case: n=3 and all degrees 2? Actually with 3 vertices, each vertex degree? In a path of 3, the middle vertex degree 2, endpoints degree 1. So degrees 1,2,1. So condition degree≤2 holds. So no -1.
Now, what about a tree with n=3 but the edges are such that it's a star (center degree 2, leaves degree 1). That's exactly a path. So okay.
Thus final answer.
Now, I'll write solution in C++.
Pseudo:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int n;
cin >> n;
vector<vector> cost(3, vector(n));
for (int c = 0; c < 3; ++c) {
for (int i = 0; i < n; ++i) {
cin >> cost[c][i];
}
}
vector<vector> adj(n);
for (int i = 0; i < n-1; ++i) {
int u, v;
cin >> u >> v;
--u; --v;
adj[u].push_back(v);
adj[v].push_back(u);
}
// check degree
for (int i = 0; i < n; ++i) {
if (adj[i].size() > 2) {
cout << -1 << endl;
return 0;
}
}
// find leaf
int start = -1;
for (int i = 0; i < n; ++i) {
if (adj[i].size() == 1) {
start = i;
break;
}
}
// construct order
vector order;
int prev = -1;
int cur = start;
while (true) {
order.push_back(cur);
int nxt = -1;
for (int nb : adj[cur]) {
if (nb != prev) {
nxt = nb;
break;
}
}
if (nxt == -1) break;
prev = cur;
cur = nxt;
}
// order size should be n, but in case something off, check
if (order.size() != n) {
// shouldn't happen
cout << -1 << endl;
return 0;
}
vector pos(n);
for (int i = 0; i < n; ++i) {
pos[order[i]] = i;
}
// permutations
vector<array<int,3>> perms = {{0,1,2},{0,2,1},{1,0,2},{1,2,0},{2,0,1},{2,1,0}};
ll min_cost = 1e18;
int best_perm_idx = -1;
for (int pidx = 0; pidx < 6; ++pidx) {
const auto& perm = perms[pidx];
ll total = 0;
for (int i = 0; i < n; ++i) {
int v = order[i];
int col = perm[i % 3];
total += cost[col][v];
}
if (total < min_cost) {
min_cost = total;
best_perm_idx = pidx;
}
}
cout << min_cost << "\n";
// output colors
const auto& best_perm = perms[best_perm_idx];
for (int v = 0; v < n; ++v) {
int idx = pos[v];
int col = best_perm[idx % 3] + 1; // convert 0-based to 1-based
cout << col;
if (v != n-1) cout << " ";
}
cout << endl;
return 0;
}
Check with examples.
Now one nuance: When n is large, reading with cin and large numbers, use faster I/O. We already used ios. Good.
Now test with sample inputs manually.
Sample1:
n=3, costs: as given. edges: 1-2,2-3. Adj lists: deg1=1, deg2=2, deg3=1 => all ≤2. start leaf could be 1 or 3. Suppose start=1 (deg1). Traverse: order: 1,2,3. Compute perms. min cost as computed 6. best perm (0,2,1) => colors: order[1]? Actually perm indices: (0,2,1) means for i%3=0 -> col0=1, i%3=1 -> col2=3, i%3=2 -> col1=2. So for v1 (i=0):1, v2 (i=1):3, v3 (i=2):2 => output "1 3 2". Good.
Now consider if the tree is a path but we start from leaf that is not the "first" leaf? That's fine.
Now confirm that the enumeration of perms uses the correct orientation. For a given order, the assignment derived from a perm will always satisfy condition? Let's verify: For any perm, the coloring is periodic with period 3, so all consecutive triples are permutations of the three colors, thus distinct. So valid.
Thus solution correct.
Now consider if there is a tree with n=3 but edges are 1-2,1-3? That's a star with center 1 degree 2, leaves 2 and 3 degree 1. That's a path? Actually it's a tree that is not a simple path if you consider shape: center connected to two leaves. But is it a path? The vertices can be ordered as 2-1-3, that's a path: edges: 2-1 and 1-3. So it's still a path. So degree pattern: 1: deg2, 2:deg1,3:deg1. So it's a path. So condition holds.
Thus any tree with max degree ≤2 is essentially a path (maybe not a straight line but can be thought of as a line). So good.
Now implement.
But we must ensure to output -1 if no good painting exists. That's when any degree >2. That's all.
But is there any scenario where degree ≤2 but still no good painting? For a path, we have at least one painting? Actually for any path length n≥3, there exist 6 colorings (provided we have three colors). So always exists. So if degree≤2, there is always at least one good painting. So -1 only for degree>2.
Thus finalize.
Now double-check: Is there any possibility that the tree is a path but with n=2? Not allowed. So fine.
Now test with random small n to ensure consistency.
Now potential pitfalls: The order traversal: need to handle case where n=1? Not allowed. For n=2? Not allowed. So loop condition works: start leaf, then while true: get neighbor not equal to prev. When cur is leaf (except start), it will have one neighbor (prev), so next = -1, break. So order ends correctly.
Now also need to ensure that we compute pos for each vertex correctly: assign index in order.
Now note: The costs can be large, use long long. Use 1e18 as INF.
Now we can output.
Thus final code.
I'll also mention that we can use array<int,3> for permutations.
Now I'm ready to write final answer.
But I'm thinking: Could there be a tree with a vertex of degree 2 but still not a simple path? Actually any tree with max degree 2 is a path. So yes.
Now code.
We'll produce final solution.
But also consider that the tree might be disconnected? No, it's guaranteed a tree.
Thus we are done.
Now finalize answer. ```cpp
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
code
int n;
cin >> n;
vector<vector<ll>> cost(3, vector<ll>(n));
for (int c = 0; c < 3; ++c) {
for (int i = 0; i < n; ++i) {
cin >> cost[c][i];
}
}
vector<vector<int>> adj(n);
for (int i = 0; i < n - 1; ++i) {
int u, v;
cin >> u >> v;
--u; --v;
adj[u].push_back(v);
adj[v].push_back(u);
}
// The condition forces the tree to be a path (max degree ≤ 2)
for (int i = 0; i < n; ++i) {
if (adj[i].size() > 2) {
cout << "-1\n";
return 0;
}
}
// Find a leaf (endpoint of the path)
int start = -1;
for (int i = 0; i < n; ++i) {
if (adj[i].size() == 1) {
start = i;
break;
}
}
// Linearize the path
vector<int> order;
int prev = -1, cur = start;
while (true) {
order.push_back(cur);
int nxt = -1;
for (int nb : adj[cur]) {
if (nb != prev) {
nxt = nb;
break;
}
}
if (nxt == -1) break;
prev = cur;
cur = nxt;
}
// Position of each vertex in the order (0‑based)
vector<int> pos(n);
for (int i = 0; i < n; ++i) {
pos[order[i]] = i;
}
// All 6 permutations of the three colors (0,1,2)
vector<array<int,3>> perms = {
{0,1,2}, {0,2,1}, {1,0,2},
{1,2,0}, {2,0,1}, {2,1,0}
};
ll best_cost = 1e18;
int best_idx = -1;
// Evaluate each permutation
for (int idx = 0; idx < 6; ++idx) {
const auto& perm = perms[idx];
ll total = 0;
for (int i = 0; i < n; ++i) {
int v = order[i];
int col = perm[i % 3];
total += cost[col][v];
}
if (total < best_cost) {
best_cost = total;
best_idx = idx;
}
}
cout << best_cost << '\n';
const auto& best_perm = perms[best_idx];
for (int v = 0; v < n; ++v) {
int p = pos[v];
cout << best_perm[p % 3] + 1; // convert to 1‑based colour numbers
if (v != n - 1) cout << ' ';
}
cout << '\n';
return 0;