Road Reform (Codeforces 1468J)
Tags: Greedy, dsu

There are $$$n$$$ cities and $$$m$$$ bidirectional roads in Berland. The $$$i$$$-th road connects the cities $$$x_i$$$ and $$$y_i$$$, and has the speed limit $$$s_i$$$. The road network allows everyone to get from any city to any other city. The Berland Transport Ministry is planning a road reform.First of all, maintaining all $$$m$$$ roads is too costly, so $$$m - (n - 1)$$$ roads will be demolished in such a way that the remaining $$$(n - 1)$$$ roads still allow to get to any city from any other city. Formally, the remaining roads should represent an undirected tree.Secondly, the speed limits on the remaining roads might be changed. The changes will be done sequentially, each change is either increasing the speed limit on some road by $$$1$$$, or decreasing it by $$$1$$$. Since changing the speed limit requires a lot of work, the Ministry wants to minimize the number of changes.The goal of the Ministry is to have a road network of $$$(n - 1)$$$ roads with the maximum speed limit over all roads equal to exactly $$$k$$$. They assigned you the task of calculating the minimum number of speed limit changes they have to perform so the road network meets their requirements.For example, suppose the initial map of Berland looks like that, and $$$k = 7$$$:  Then one of the optimal courses of action is to demolish the roads $$$1$$$–$$$4$$$ and $$$3$$$–$$$4$$$, and then decrease the speed limit on the road $$$2$$$–$$$3$$$ by $$$1$$$, so the resulting road network looks like that:  

Input: The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases.The first line of each test case contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$; $$$n - 1 \le m \le \min(2 \cdot 10^5, \frac{n(n-1)}{2})$$$; $$$1 \le k \le 10^9$$$) — the number of cities, the number of roads and the required maximum speed limit, respectively.Then $$$m$$$ lines follow. The $$$i$$$-th line contains three integers $$$x_i$$$, $$$y_i$$$ and $$$s_i$$$ ($$$1 \le x_i, y_i \le n$$$; $$$x_i \ne y_i$$$; $$$1 \le s_i \le 10^9$$$) — the cities connected by the $$$i$$$-th road and the speed limit on it, respectively. All roads are bidirectional.The road network in each test case is connected (that is, it is possible to reach any city from any other city by traveling along the road), and each pair of cities is connected by at most one road.The sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$. Similarly, the sum of $$$m$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

Output: For each test case, print one integer — the minimum number of changes the Ministry has to perform so that the maximum speed limit among the remaining $$$(n - 1)$$$ roads is exactly $$$k$$$.

Note: The explanation for the example test:The first test case is described in the problem statement.In the second test case, the road network initially looks like that:  The Ministry can demolish the roads $$$1$$$–$$$2$$$, $$$3$$$–$$$2$$$ and $$$3$$$–$$$4$$$, and then increase the speed limit on the road $$$1$$$–$$$4$$$ three times.In the third test case, the road network already meets all the requirements.In the fourth test case, it is enough to demolish the road $$$1$$$–$$$2$$$ so the resulting road network meets the requirements.

Sample Inputs:
4
4 5 7
4 1 3
1 2 5
2 3 8
2 4 1
3 4 4
4 6 5
1 2 1
1 3 1
1 4 2
2 4 1
4 3 1
3 2 1
3 2 10
1 2 8
1 3 10
5 5 15
1 2 17
3 1 15
2 3 10
1 4 14
2 5 8

Sample Outputs:
1
3
0
0

Solution (Python):
import sys
input = sys.stdin.readline
from math import inf

def find(u):
    if pa[u] != u:
        pa[u] = find(pa[u])
    return pa[u]

def union(u, v):
    u = find(u)
    v = find(v)
    if u < v:
        pa[v] = u
    else:
        pa[u] = v
for _ in range(int(input())):
    (n, m, k) = map(int, input().split())
    edges = []
    relax = inf
    for _ in range(m):
        (x, y, s) = map(int, input().split())
        x -= 1
        y -= 1
        edges.append((max(0, s - k), x, y))
        relax = min(relax, abs(s - k))
    pa = [i for i in range(n)]
    result = ct = 0
    for (w, u, v) in sorted(edges):
        if find(u) != find(v):
            union(u, v)
            result += w
            ct += 1
            if ct == n - 1:
                break
    print(result) if result else print(relax)

Solution (Python):
import math
from sys import stdin

def uf_find(n, p):
    ufl = []
    while p[n] != n:
        ufl.append(n)
        n = p[n]
    for i in ufl:
        p[i] = n
    return n

def uf_union(a, b, p, rank):
    ap = uf_find(a, p)
    bp = uf_find(b, p)
    if ap == bp:
        return True
    else:
        if rank[ap] > rank[bp]:
            p[bp] = ap
        elif rank[ap] < rank[bp]:
            p[ap] = bp
        else:
            p[bp] = ap
            rank[ap] += 1
        return False
tt = int(stdin.readline())
for loop in range(tt):
    (n, m, k) = map(int, stdin.readline().split())
    under = []
    over = []
    for i in range(m):
        (x, y, s) = map(int, stdin.readline().split())
        x -= 1
        y -= 1
        if s <= k:
            under.append((s, x, y))
        else:
            over.append((s, x, y))
    under.sort()
    over.sort()
    ans = float('inf')
    cnt = 0
    p = [i for i in range(n)]
    rank = [0] * n
    for (c, x, y) in under:
        if not uf_union(x, y, p, rank):
            cnt += 1
    if cnt == n - 1 and len(under) > 0:
        ans = min(ans, k - under[-1][0])
    if cnt != n - 1:
        tmpsum = 0
        for (c, x, y) in over:
            if not uf_union(x, y, p, rank):
                cnt += 1
                tmpsum += c - k
                if cnt == n - 1:
                    ans = min(ans, tmpsum)
    elif len(over) > 0:
        ans = min(ans, over[0][0] - k)
    print(ans)

Solution (Python):
import sys

def load_sys():
    return sys.stdin.readlines()

def load_local():
    with open('input.txt', 'r') as f:
        input = f.readlines()
    return input

def f(n, m, k, edges):
    edges.sort(key=lambda x: x[-1])
    UF = {x: x for x in range(1, n + 1)}

    def find(x):
        if UF[x] != x:
            UF[x] = find(UF[x])
        return UF[x]

    def union(x, y):
        UF[find(y)] = find(x)
        return
    edges_cnt = 0
    ans = 0
    for (idx, (i, j, w)) in enumerate(edges):
        if w < k:
            if find(i) != find(j):
                union(i, j)
                edges_cnt += 1
        else:
            if edges_cnt >= n - 1:
                return min(w - k, k - edges[idx - 1][-1])
            if find(i) != find(j):
                union(i, j)
                edges_cnt += 1
                ans += w - k
            if edges_cnt >= n - 1:
                return ans
    return k - w
input = load_sys()
i = 1
while i < len(input):
    (n, m, k) = map(int, input[i].split())
    edges = []
    for _ in range(m):
        i += 1
        (x, y, w) = map(int, input[i].split())
        edges.append((x, y, w))
    i += 1
    print(f(n, m, k, edges))