Baldman and the military (Codeforces 42E)
Tags: Others, trees

Baldman is a warp master. He possesses a unique ability — creating wormholes! Given two positions in space, Baldman can make a wormhole which makes it possible to move between them in both directions. Unfortunately, such operation isn't free for Baldman: each created wormhole makes him lose plenty of hair from his head.Because of such extraordinary abilities, Baldman has caught the military's attention. He has been charged with a special task. But first things first.The military base consists of several underground objects, some of which are connected with bidirectional tunnels. There necessarily exists a path through the tunnel system between each pair of objects. Additionally, exactly two objects are connected with surface. For the purposes of security, a patrol inspects the tunnel system every day: he enters one of the objects which are connected with surface, walks the base passing each tunnel at least once and leaves through one of the objects connected with surface. He can enter and leave either through the same object, or through different objects. The military management noticed that the patrol visits some of the tunnels multiple times and decided to optimize the process. Now they are faced with a problem: a system of wormholes needs to be made to allow of a patrolling which passes each tunnel exactly once. At the same time a patrol is allowed to pass each wormhole any number of times.This is where Baldman comes to operation: he is the one to plan and build the system of the wormholes. Unfortunately for him, because of strict confidentiality the military can't tell him the arrangement of tunnels. Instead, they insist that his system of portals solves the problem for any arrangement of tunnels which satisfies the given condition. Nevertheless, Baldman has some information: he knows which pairs of objects he can potentially connect and how much it would cost him (in hair). Moreover, tomorrow he will be told which objects (exactly two) are connected with surface. Of course, our hero decided not to waste any time and calculate the minimal cost of getting the job done for some pairs of objects (which he finds likely to be the ones connected with surface). Help Baldman!

Input: First line of the input contains a single natural number n (2 ≤ n ≤ 100000) — the number of objects on the military base. The second line — one number m (1 ≤ m ≤ 200000) — the number of the wormholes Baldman can make. The following m lines describe the wormholes: each line contains three integer numbers a, b, c (1 ≤ a, b ≤ n, 1 ≤ c ≤ 100000) — the numbers of objects which can be connected and the number of hair Baldman has to spend to make this wormhole.The next line contains one natural number q (1 ≤ q ≤ 100000) — the number of queries. Finally, the last q lines contain a description of one query each — a pair of numbers of different objects ai, bi (1 ≤ ai, bi ≤ n, ai ≠ bi). There could be more than one wormhole between a pair of objects.

Output: Your program should output q lines, one for each query. The i-th line should contain a single integer number — the answer for i-th query: the minimum cost (in hair) of a system of wormholes allowing the optimal patrol for any system of tunnels (satisfying the given conditions) if ai and bi are the two objects connected with surface, or "-1" if such system of wormholes cannot be made.


Sample Inputs:
2
1
1 2 3
1
1 2

3
1
1 2 3
2
1 2
1 3

Sample Outputs:
0

-1
3

Solution (Python):
import sys
from typing import List, Tuple
readline = sys.stdin.readline

class UionFind:

    def __init__(self, n: int):
        self.data = list(range(n))
        self.rank = [1] * n
        self.count = n

    def resize(self, n: int):
        self.data = list(range(n))
        self.rank = [1] * n
        self.count = n

    def find(self, x: int) -> int:
        t = x
        while t != self.data[t]:
            t = self.data[t]
        while x != self.data[x]:
            (self.data[x], x) = (t, self.data[x])
        return self.data[x]

    def union(self, x: int, y: int):
        (x, y) = (self.find(x), self.find(y))
        if x == y:
            return
        if self.rank[x] < self.rank[y]:
            (x, y) = (y, x)
        elif self.rank[x] == self.rank[y]:
            self.rank[x] += 1
        self.data[y] = x
        self.count -= 1

class LCA:

    def __init__(self, tree: list, root: int) -> None:

        def dfs(node: int, parent: int, depth: int):
            stk = [(node, parent, depth)]
            while stk:
                (node, parent, depth) = stk.pop()
                self.depth[node] = depth
                for (child, cost) in tree[node]:
                    if child == parent:
                        continue
                    self.table[0][child] = (node, cost)
                    stk.append((child, node, depth + 1))
        self.table = [[(-1, 0) for _ in tree] for _ in range(20)]
        self.depth = [0] * len(tree)
        dfs(root, -1, 0)
        for i in range(19):
            for j in range(len(tree)):
                if self.table[i][j][0] < 0:
                    continue
                (a1, c1) = self.table[i][j]
                (a2, c2) = self.table[i][a1]
                self.table[i + 1][j] = (a2, max(c1, c2))

    def query(self, u: int, v: int) -> int:

        def go_up(node: int, step: int) -> tuple:
            cost = 0
            pace = 18
            while step > 0:
                while 2 ** pace > step:
                    pace -= 1
                (a, c) = self.table[pace][node]
                cost = max(cost, c)
                node = a
                step -= 2 ** pace
            return (node, cost)
        cost = 0
        if self.depth[u] > self.depth[v]:
            (u, cost) = go_up(u, self.depth[u] - self.depth[v])
        elif self.depth[u] < self.depth[v]:
            (v, cost) = go_up(v, self.depth[v] - self.depth[u])
        if v == u:
            return cost
        pace = 18
        while u != v:
            while pace > 0 and self.table[pace][u][0] == self.table[pace][v][0]:
                pace -= 1
            (u, c1) = self.table[pace][u]
            (v, c2) = self.table[pace][v]
            cost = max([cost, c1, c2])
        return cost
N = 0
forest = []
depth = []
edges = []
queries = []
roots = []
uf = UionFind(1)
total_cost = 0

def read():
    global N, edges
    N = int(readline().strip())
    m = int(readline().strip())
    for _ in range(m):
        (u, v, c) = list(map(int, readline().split()))
        edges.append((u - 1, v - 1, c))
    q = int(readline().strip())
    for _ in range(q):
        (u, v) = list(map(int, readline().split()))
        queries.append((u - 1, v - 1))

def build_mst(N: int, edges: List[tuple], roots: List[int]) -> List[List[Tuple[int]]]:
    global total_cost
    total_cost = 0
    graph = [[] for _ in range(N)]
    uf.resize(N)
    edges.sort(key=lambda x: x[-1])
    for (u, v, c) in edges:
        if uf.find(u) == uf.find(v):
            continue
        uf.union(u, v)
        graph[u].append((v, c))
        graph[v].append((u, c))
        total_cost += c
    roots.extend({uf.find(i) for i in range(N)})
    return graph

def solve() -> list:
    result = []
    if uf.count == 2:
        for (u, v) in queries:
            if uf.find(u) == uf.find(v):
                result.append(-1)
            else:
                result.append(total_cost)
    elif uf.count > 2:
        result = [-1] * len(queries)
    else:
        lca = LCA(forest, roots[0])
        for (u, v) in queries:
            result.append(total_cost - lca.query(u, v))
    return result

def write(result: list):
    for n in result:
        print(n)
read()
forest = build_mst(N, edges, roots)
write(solve())

Solution (Python):
import sys
from typing import List, Set, Tuple
readline = sys.stdin.readline

class UionFind:

    def __init__(self, n: int):
        self.data = list(range(n))
        self.rank = [1] * n
        self.count = n

    def resize(self, n: int):
        self.data = list(range(n))
        self.rank = [1] * n
        self.count = n

    def find(self, x: int) -> int:
        t = x
        while t != self.data[t]:
            t = self.data[t]
        while x != self.data[x]:
            (self.data[x], x) = (t, self.data[x])
        return self.data[x]

    def union(self, x: int, y: int):
        (x, y) = (self.find(x), self.find(y))
        if x == y:
            return
        if self.rank[x] < self.rank[y]:
            (x, y) = (y, x)
        elif self.rank[x] == self.rank[y]:
            self.rank[x] += 1
        self.data[y] = x
        self.count -= 1

class LCA:

    def __init__(self, tree: list, root: int) -> None:

        def dfs(node: int, parent: int, depth: int):
            stk = [(node, parent, depth)]
            while stk:
                (node, parent, depth) = stk.pop()
                self.depth[node] = depth
                for (child, cost) in tree[node]:
                    if child == parent:
                        continue
                    self.table[0][child] = (node, cost)
                    stk.append((child, node, depth + 1))
        self.table = [[(-1, 0) for _ in tree] for _ in range(20)]
        self.depth = [0] * len(tree)
        dfs(root, -1, 0)
        for i in range(19):
            for j in range(len(tree)):
                if self.table[i][j][0] < 0:
                    continue
                (a1, c1) = self.table[i][j]
                (a2, c2) = self.table[i][a1]
                self.table[i + 1][j] = (a2, max(c1, c2))

    def query(self, u: int, v: int) -> int:

        def go_up(node: int, step: int) -> tuple:
            cost = 0
            pace = 18
            while step > 0:
                while 2 ** pace > step:
                    pace -= 1
                (a, c) = self.table[pace][node]
                cost = max(cost, c)
                node = a
                step -= 2 ** pace
            return (node, cost)
        cost = 0
        if self.depth[u] > self.depth[v]:
            (u, cost) = go_up(u, self.depth[u] - self.depth[v])
        elif self.depth[u] < self.depth[v]:
            (v, cost) = go_up(v, self.depth[v] - self.depth[u])
        if v == u:
            return cost
        pace = 18
        while u != v:
            while pace > 0 and self.table[pace][u][0] == self.table[pace][v][0]:
                pace -= 1
            (u, c1) = self.table[pace][u]
            (v, c2) = self.table[pace][v]
            cost = max([cost, c1, c2])
        return cost
N = 0
forest = []
depth = []
edges = []
queries = []
roots = []
uf = UionFind(1)
total_cost = 0

def read():
    global N, edges
    N = int(readline().strip())
    m = int(readline().strip())
    for _ in range(m):
        (u, v, c) = list(map(int, readline().split()))
        edges.append((u - 1, v - 1, c))
    q = int(readline().strip())
    for _ in range(q):
        (u, v) = list(map(int, readline().split()))
        queries.append((u - 1, v - 1))

def build_mst(N: int, edges: List[tuple], roots: List[int]) -> List[List[Tuple[int]]]:
    global total_cost
    total_cost = 0
    graph = [[] for _ in range(N)]
    uf.resize(N)
    edges.sort(key=lambda x: x[-1])
    for (u, v, c) in edges:
        if uf.find(u) == uf.find(v):
            continue
        uf.union(u, v)
        graph[u].append((v, c))
        graph[v].append((u, c))
        total_cost += c
    roots.extend({uf.find(i) for i in range(N)})
    return graph

def solve() -> list:
    result = []
    if uf.count == 2:
        for (u, v) in queries:
            if uf.find(u) == uf.find(v):
                result.append(-1)
            else:
                result.append(total_cost)
    elif uf.count > 2:
        result = [-1] * len(queries)
    else:
        lca = LCA(forest, roots[0])
        for (u, v) in queries:
            result.append(total_cost - lca.query(u, v))
    return result

def write(result: list):
    for n in result:
        print(n)
read()
forest = build_mst(N, edges, roots)
write(solve())

Solution (Python):
import sys
from typing import List, Set, Tuple
readline = sys.stdin.readline

class UionFind:

    def __init__(self, n: int):
        self.data = list(range(n))
        self.rank = [1] * n
        self.count = n

    def resize(self, n: int):
        self.data = list(range(n))
        self.rank = [1] * n
        self.count = n

    def find(self, x: int) -> int:
        t = x
        while t != self.data[t]:
            t = self.data[t]
        while x != self.data[x]:
            (self.data[x], x) = (t, self.data[x])
        return self.data[x]

    def union(self, x: int, y: int):
        (x, y) = (self.find(x), self.find(y))
        if x == y:
            return
        if self.rank[x] < self.rank[y]:
            (x, y) = (y, x)
        elif self.rank[x] == self.rank[y]:
            self.rank[x] += 1
        self.data[y] = x
        self.count -= 1

class LCA:

    def __init__(self, tree: list, root: int) -> None:

        def dfs(node: int, parent: int, depth: int):
            stk = [(node, parent, depth)]
            while stk:
                (node, parent, depth) = stk.pop()
                self.depth[node] = depth
                for (child, cost) in tree[node]:
                    if child == parent:
                        continue
                    self.table[0][child] = (node, cost)
                    stk.append((child, node, depth + 1))
        self.table = [[(-1, 0) for _ in tree] for _ in range(32)]
        self.depth = [0] * len(tree)
        dfs(root, -1, 0)
        for i in range(31):
            for j in range(len(tree)):
                if self.table[i][j][0] < 0:
                    continue
                (a1, c1) = self.table[i][j]
                (a2, c2) = self.table[i][a1]
                self.table[i + 1][j] = (a2, max(c1, c2))

    def query(self, u: int, v: int) -> int:

        def go_up(node: int, step: int) -> tuple:
            cost = 0
            pace = 30
            while step > 0:
                while 2 ** pace > step:
                    pace -= 1
                (a, c) = self.table[pace][node]
                cost = max(cost, c)
                node = a
                step -= 2 ** pace
            return (node, cost)
        cost = 0
        if self.depth[u] > self.depth[v]:
            (u, cost) = go_up(u, self.depth[u] - self.depth[v])
        elif self.depth[u] < self.depth[v]:
            (v, cost) = go_up(v, self.depth[v] - self.depth[u])
        if v == u:
            return cost
        pace = 30
        while u != v:
            while pace > 0 and self.table[pace][u][0] == self.table[pace][v][0]:
                pace -= 1
            (u, c1) = self.table[pace][u]
            (v, c2) = self.table[pace][v]
            cost = max([cost, c1, c2])
        return cost
N = 0
forest = []
depth = []
edges = []
queries = []
roots = []
uf = UionFind(1)
total_cost = 0

def read():
    global N, edges
    N = int(readline().strip())
    m = int(readline().strip())
    for _ in range(m):
        (u, v, c) = list(map(int, readline().split()))
        edges.append((u - 1, v - 1, c))
    q = int(readline().strip())
    for _ in range(q):
        (u, v) = list(map(int, readline().split()))
        queries.append((u - 1, v - 1))

def build_mst(N: int, edges: List[tuple], roots: List[int]) -> List[Set[Tuple[int]]]:
    global total_cost
    total_cost = 0
    graph = [set() for _ in range(N)]
    uf.resize(N)
    edges.sort(key=lambda x: x[-1])
    for (u, v, c) in edges:
        if uf.find(u) == uf.find(v):
            continue
        uf.union(u, v)
        graph[u].add((v, c))
        graph[v].add((u, c))
        total_cost += c
    roots.extend({uf.find(i) for i in range(N)})
    return graph

def solve() -> list:
    result = []
    if uf.count == 2:
        for (u, v) in queries:
            if uf.find(u) == uf.find(v):
                result.append(-1)
            else:
                result.append(total_cost)
    elif uf.count > 2:
        result = [-1] * len(queries)
    else:
        lca = LCA(forest, roots[0])
        for (u, v) in queries:
            result.append(total_cost - lca.query(u, v))
    return result

def write(result: list):
    for n in result:
        print(n)
read()
forest = build_mst(N, edges, roots)
write(solve())