Tree Edges Coloring
Practice
3.8 (17 votes)
Medium
Approved
Problem
71% Success 609 Attempts 30 Points 4s Time Limit 256MB Memory 1024 KB Max Code

View Russian Translation

You are given a tree T of n nodes. The nodes in the tree are numbered 1 through n. Let's consider some set of different colors numbered 1 through \(n - 1\). Each color costs differently. You are given a sequence \(cost_1, cost_2, ..., cost_{n-1}\) of the color costs.

For each edge, you should choose exactly one color in such a way that no two incident edges have the same color and the sum of the chosen color costs is as minimal as possible.

More formally, let's assign some unique integer from 1 to \(n - 1\) to each of the edges of T. A sequence \(c_1, c_2, ..., c_{n-1}\) (\(1 \le c_k \le n - 1\)) is called an edge coloring of the tree; \(c_k\) is called the color of the k'th edge. An edge coloring is called valid, if there is no such a pair of edges, that share a common node and have the same color.

The cost of an edge coloring is the sum of the color costs for all the edges of the tree. Your task is to find the cost of the cheapest valid edge coloring.

Input format

The first line contains one integer t denoting the number of test cases in the input.

The first line of each test case description contains an integer n.

The second line contains \(n - 1\) positive integers denoting \(cost_1, cost_2, ..., cost_{n-1}\).

Each of the next \(n - 1\) lines contains two integers u and v denoting an edge of the tree.

Output format

For each test case, output a single integer: the cost of the cheapest valid edge coloring.

Constraints

  • \(1 \le t \le 16\)
  • \(1 \le n \le 100\)
  • \(1 \le cost_{color} \le 1000\)

Subtasks

Extra constraints Points Which tests
\(n \le 8\) 30 1
\(n \le 10\) 10 2
\(n \le 25\) 10 3
\(n \le 50\) 10 4
\(n \le 70\) 10 5
no extra constraints 30 6-8

Please login to use the editor

You need to be logged in to access the code editor

Loading...

Please wait while we load the editor

Loading...
Results
Custom Input
Run your code to see the output
Submissions
Please login to view your submissions
Similar Problems
Points:20
18 votes
Tags:
Hash tableData StructuresEasyOpenApprovedHash function
Points:20
Tags:
MathematicsEasyMathematicsMathamatics
Points:30
3 votes
Tags:
RecursionDynamic ProgrammingMedium