IITWPC4I - Petya and the Road Repairs


Petya is the mayor of a city named Mayapur. In the morning, everybody likes to drink hot tea in bed, and the citizens need milk to take with their tea. For this purpose, they should be able to reach at least some milkman in the city. There are m bi-directional roads in the city but all of them are currently unrepaired, hence not in a state of use.
Petya cares about his city a lot and intends to repair some of these roads, so that every citizen is connected to at least one milkman. For repairing each road he needs to pay a cost. He would like to minimize the cost of this project. Note that a milkman does not need to go to some other milkman for milk as he can take milk from himsaelf. 

Help Petya in finding out the minimum cost needed to repair the roads in the given way. If it is not possible for a citizen to connect to any of the milkmen, output "impossible" (without quotes).

Input

The first line contains T: the number of test cases. (1 <= T <= 100)

For each test case, the first line contains two space-seperated numbers n, m: n is the number of citizens in Mayapur and m denotes the number of unrepaired roads (1 <= n <= 10^5, 1 <= m <= min (n * (n - 1) / 2, 2 * 10^5)).

The next line contains n space-separated integers, which are either 0 or 1, denoting for successive citizens whether they are a milkman or not.

Then, for each of the next m lines, each line contains three space-seperated integers u, v and c, denoting that there exists a unrepaired road between u and v such that the cost of repairing of road is c. (1 <= u, v <= n and u != v, 1 <= c <= 10^9.) 

Output

For each test case output the cost as required.

Example

Input:
1
5 7
0 1 0 1 0
1 2 11
1 3 1
1 5 17
2 3 1
3 5 18
4 5 3
2 4 5
Output:
5

hide comments
zemotacqy: 2018-05-18 13:42:28

Read the question carefully.
Try this test Case:
1
5 9
0 0 0 0 1
1 2 12
2 3 3
3 4 7
5 1 5
3 2 5
2 3 2
2 1 4
1 5 3
Correct Answer: 16

nadstratosfer: 2018-03-11 17:34:23

Watch out for blanklines in input when solving with Python.

The problem is not really a straightforward DSU / MST, at least if you count your cycles and don't want the code to do stupid stuff. Or perhaps I missed some key observation, eitherway enjoyed having to figure out an efficient approach on my own.

chetan4060: 2018-01-27 14:25:43

AC in one go:-)

codefield: 2018-01-19 21:57:55

kruskal rocks as usual

Last edit: 2018-01-19 22:00:18
sahil_1994: 2017-11-02 23:12:34

is the city connected or not ??

code_aim: 2017-10-23 07:02:08

Good question with tricky test case!!

babur: 2017-06-27 09:28:00

Its a classic Prim's algorithm question...

sas1905: 2017-06-12 05:37:54

Strong and tricky test cases..!!

akt_1998: 2017-06-11 22:48:36

prims ;)

siddharth_0196: 2017-03-25 20:13:32

DSU! :D


Added by:praveen123
Date:2014-02-03
Time limit:1s
Source limit:50000B
Memory limit:1536MB
Cluster: Cube (Intel G860)
Languages:All except: ASM64
Resource:IITK ACA CSE online judge