CF BUDDY
← Problems·

1777E · Edge Reverse

2200 · binary search, dfs and similar, graphs

Problem: You will be given a weighted directed graph of nn nodes and mm directed edges, where the ii-th edge has a weight of wiw_i (1im1 \le i \le m).

You need to reverse some edges of this graph so that there is at least one node in the graph from which every other node is reachable. The cost of these reversals is equal to the maximum weight of all reversed edges. If no edge reversal is required, assume the cost to be 00.

It is guaranteed that no self-loop or duplicate edge exists.

Find the minimum cost required for completing the task. If there is no solution, print a single integer 1-1.

Input Format: Each test contains multiple test cases. The first line contains the number of test cases tt (1t1051 \le t \le 10^5). The description of the test cases follows.

Each test case begins with a line containing two integers nn and mm (2n21052 \le n \le 2 \cdot 10^5, 1m21051 \le m \le 2 \cdot 10^5) — the number of nodes in the graph and the number of edges in the graph.

The next mm lines of each test case contain 33 integers each — uu, vv, ww (1u,vn1 \le u, v \le n, 1w1091 \le w \le 10^9), indicating an edge from uu to vv with a weight of ww. It is guaranteed that no edge connects a vertex to itself, and no pair of edges share the same origin and destination simultaneously.

It is guaranteed that the sum of nn and the sum of mm over all test cases do not exceed 21052 \cdot 10^5.

Output Format: For each test case, output the minimum cost. If there is no solution, print 1-1.

Note: In the first test case, an edge exists from 11 to 22, so all nodes are reachable (from 11).

In the second test case, no nodes are reachable from any node no matter what edges we reverse, so the answer is 1-1.

In the third test case, reversing the 44-th or 55-th edge allows all nodes to be reachable from 11. We choose the 55-th edge here because its weight is smaller.

Sample Cases

Case 1

Input

4
2 1
1 2 3
5 4
1 2 10
2 3 10
3 1 10
4 5 10
4 5
1 2 10000
2 3 20000
1 3 30000
4 2 500
4 3 20
4 5
1 2 10000
2 3 20000
1 3 30000
4 2 5
4 3 20

Output

0
-1
20
5

Similar problems

00:00:00
Loading editor…
Welcome! I'm your coding tutor for this problem. Use the chips below to reveal stored hints or get AI feedback on your code. I'll guide you step by step — never giving away the solution.

Sign in to unlock AI tutor feedback