Edge Reverse (Codeforces 1777E)
Tags: Others, trees

You will be given a weighted directed graph of $$$n$$$ nodes and $$$m$$$ directed edges, where the $$$i$$$-th edge has a weight of $$$w_i$$$ ($$$1 \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 $$$0$$$.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$$$.

Input: Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^5$$$). The description of the test cases follows.Each test case begins with a line containing two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$1 \le m \le 2 \cdot 10^5$$$) — the number of nodes in the graph and the number of edges in the graph.The next $$$m$$$ lines of each test case contain $$$3$$$ integers each — $$$u$$$, $$$v$$$, $$$w$$$ ($$$1 \le u, v \le n$$$, $$$1 \le w \le 10^9$$$), indicating an edge from $$$u$$$ to $$$v$$$ with a weight of $$$w$$$. 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 $$$n$$$ and the sum of $$$m$$$ over all test cases do not exceed $$$2 \cdot 10^5$$$.

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

Note: In the first test case, an edge exists from $$$1$$$ to $$$2$$$, so all nodes are reachable (from $$$1$$$).In the second test case, no nodes are reachable from any node no matter what edges we reverse, so the answer is $$$-1$$$.In the third test case, reversing the $$$4$$$-th or $$$5$$$-th edge allows all nodes to be reachable from $$$1$$$. We choose the $$$5$$$-th edge here because its weight is smaller.

Sample Inputs:
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

Sample Outputs:
0
-1
20
5

Solution (Python):
import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

def binary_search(c1, c2):
    c = (c1 + c2 + 1) // 2
    while abs(c1 - c2) > 1:
        c = (c1 + c2 + 1) // 2
        if ok(c):
            c2 = c
        else:
            c1 = c
    c = max(c - 1, 0)
    while c < len(w0) and (not ok(c)):
        c += 1
    return -1 if c == len(w0) else w0[c]

def bfs(s, z, visit):
    (q, k) = ([s], 0)
    visit[s] = 1
    while len(q) ^ k:
        i = q[k]
        for v in range(s0[i], s0[i + 1]):
            j = G[v]
            if w[v] <= z and (not visit[j]):
                q.append(j)
                visit[j] = 1
        k += 1
    return True if len(q) == n else False

def ok(c):
    if c >= len(w0):
        return True
    z = w0[c]
    visit = [0] * (n + 1)
    for u in range(1, n + 1):
        if not visit[u]:
            bfs(u, z, visit)
            s = u
    visit = [0] * (n + 1)
    return True if s == 1 or bfs(s, z, visit) else False
t = int(input())
ans = []
for _ in range(t):
    (n, m) = map(int, input().split())
    (e, w1) = ([], [])
    s0 = [0] * (n + 3)
    for _ in range(m):
        (u, v, w) = map(int, input().split())
        e.append(u)
        e.append(v)
        s0[u + 2] += 1
        s0[v + 2] += 1
        w1.append(0)
        w1.append(w)
    for i in range(3, n + 3):
        s0[i] += s0[i - 1]
    (G, w) = ([0] * (2 * m), [0] * (2 * m))
    for i in range(2 * m):
        j = e[i] + 1
        (G[s0[j]], w[s0[j]]) = (e[i ^ 1], w1[i])
        s0[j] += 1
    w0 = list(set(sorted(w1)))
    w0.sort()
    ans0 = binary_search(0, len(w0))
    ans.append(ans0)
sys.stdout.write('\n'.join(map(str, ans)))

Solution (Python):
import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

def binary_search(c1, c2):
    c = (c1 + c2 + 1) // 2
    while abs(c1 - c2) > 1:
        c = (c1 + c2 + 1) // 2
        if ok(c):
            c2 = c
        else:
            c1 = c
    c = max(c - 1, 0)
    while c < len(w0) and (not ok(c)):
        c += 1
    return -1 if c == len(w0) else w0[c]

def ok(c):
    s0 = [0] * (n + 3)
    if c >= len(w0):
        return True
    z = w0[c]
    m0 = 2 * m
    for i in range(m):
        s0[e[2 * i] + 2] += 1
        if w1[i] <= z:
            s0[e[2 * i + 1] + 2] += 1
        else:
            m0 -= 1
    for i in range(3, n + 3):
        s0[i] += s0[i - 1]
    G = [0] * m0
    for i in range(2 * m):
        if i & 1 and w1[i // 2] > z:
            continue
        j = e[i] + 1
        G[s0[j]] = e[i ^ 1]
        s0[j] += 1
    visit = [0] * (n + 1)
    for u in range(1, n + 1):
        if visit[u]:
            continue
        (q, k) = ([u], 0)
        visit[u] = 1
        while len(q) ^ k:
            i = q[k]
            for v in range(s0[i], s0[i + 1]):
                j = G[v]
                if not visit[j]:
                    q.append(j)
                    visit[j] = 1
            k += 1
        s = u
    q = [s]
    visit = [0] * (n + 1)
    visit[s] = 1
    for k in range(n):
        if len(q) <= k:
            return False
        i = q[k]
        for v in range(s0[i], s0[i + 1]):
            j = G[v]
            if not visit[j]:
                q.append(j)
                visit[j] = 1
    return True
t = int(input())
ans = []
for _ in range(t):
    (n, m) = map(int, input().split())
    (e, w1) = ([], [])
    for _ in range(m):
        (u, v, w) = map(int, input().split())
        e.append(u)
        e.append(v)
        w1.append(w)
    w0 = [0]
    for i in w1:
        w0.append(i)
    w0 = list(set(sorted(w0)))
    w0.sort()
    ans0 = binary_search(0, len(w0))
    ans.append(ans0)
sys.stdout.write('\n'.join(map(str, ans)))

Solution (Python):
import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

def binary_search(c1, c2):
    c = (c1 + c2 + 1) // 2
    while abs(c1 - c2) > 1:
        c = (c1 + c2 + 1) // 2
        if ok(c):
            c2 = c
        else:
            c1 = c
    c = max(c - 1, 0)
    while c < len(w0) and (not ok(c)):
        c += 1
    return -1 if c == len(w0) else w0[c]

def bfs(s, z, visit):
    q = [s]
    visit[s] = 1
    for k in range(n):
        if len(q) <= k:
            return False
        i = q[k]
        for v in range(s0[i], s0[i + 1]):
            j = G[v]
            if w[v] <= z and (not visit[j]):
                q.append(j)
                visit[j] = 1
    return True

def ok(c):
    if c >= len(w0):
        return True
    z = w0[c]
    visit = [0] * (n + 1)
    for u in range(1, n + 1):
        if not visit[u]:
            bfs(u, z, visit)
            s = u
    visit = [0] * (n + 1)
    return True if s == 1 or bfs(s, z, visit) else False
t = int(input())
ans = []
for _ in range(t):
    (n, m) = map(int, input().split())
    (e, w1) = ([], [])
    s0 = [0] * (n + 3)
    for _ in range(m):
        (u, v, w) = map(int, input().split())
        e.append(u)
        e.append(v)
        s0[u + 2] += 1
        s0[v + 2] += 1
        w1.append(0)
        w1.append(w)
    for i in range(3, n + 3):
        s0[i] += s0[i - 1]
    (G, w) = ([0] * (2 * m), [0] * (2 * m))
    for i in range(2 * m):
        j = e[i] + 1
        (G[s0[j]], w[s0[j]]) = (e[i ^ 1], w1[i])
        s0[j] += 1
    w0 = list(set(sorted(w1)))
    w0.sort()
    ans0 = binary_search(0, len(w0))
    ans.append(ans0)
sys.stdout.write('\n'.join(map(str, ans)))