Valuable Paper (Codeforces 1423B)
Tags: Others, graph matchings

The pandemic is upon us, and the world is in shortage of the most important resource: toilet paper. As one of the best prepared nations for this crisis, BubbleLand promised to help all other world nations with this valuable resource. To do that, the country will send airplanes to other countries carrying toilet paper.In BubbleLand, there are $$$N$$$ toilet paper factories, and $$$N$$$ airports. Because of how much it takes to build a road, and of course legal issues, every factory must send paper to only one airport, and every airport can only take toilet paper from one factory.Also, a road can't be built between all airport-factory pairs, again because of legal issues. Every possible road has number $$$d$$$ given, number of days it takes to build that road.Your job is to choose $$$N$$$ factory-airport pairs, such that if the country starts building all roads at the same time, it takes the least amount of days to complete them.

Input: The first line contains two integers $$$N$$$ $$$(1 \leq N \leq 10^4)$$$ - number of airports/factories, and $$$M$$$ $$$(1 \leq M \leq 10^5)$$$ - number of available pairs to build a road between.On next $$$M$$$ lines, there are three integers $$$u$$$, $$$v$$$ $$$(1 \leq u,v \leq N)$$$, $$$d$$$ $$$(1 \leq d \leq 10^9)$$$ - meaning that you can build a road between airport $$$u$$$ and factory $$$v$$$ for $$$d$$$ days.

Output: If there are no solutions, output -1. If there exists a solution, output the minimal number of days to complete all roads, equal to maximal $$$d$$$ among all chosen roads.


Sample Inputs:
3 5
1 2 1
2 3 2
3 3 3
2 1 4
2 2 5

Sample Outputs:
4

Solution (Python):
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = 'x' in file.mode or 'r' not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            (self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b'\n') + (not b)
            ptr = self.buffer.tell()
            (self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            (self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode('ascii'))
        self.read = lambda : self.buffer.read().decode('ascii')
        self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def RL():
    return map(int, sys.stdin.readline().rstrip().split())

def RLL():
    return list(map(int, sys.stdin.readline().rstrip().split()))

def N():
    return int(input())

def print_list(l):
    print(' '.join(map(str, l)))
from collections import defaultdict as dc

def judge(last, key, d1, d2):
    if key > last:
        for (a, b, c) in data:
            if last < c <= key:
                d1[a].add(b)
                d2[b].add(a)
    else:
        for (a, b, c) in data:
            if key < c <= last:
                d1[a].remove(b)
                if not d1[a]:
                    del d1[a]
                d2[b].remove(a)
                if not d2[b]:
                    del d2[b]
    if len(d1.keys()) < n or len(d2.keys()) < n:
        return False
    for a in d1:
        lone = 0
        for b in d1[a]:
            if len(d2[b]) == 1:
                lone += 1
                if lone > 1:
                    return False
    for b in d2:
        lone = 0
        for a in d2[b]:
            if len(d1[a]) == 1:
                lone += 1
                if lone > 1:
                    return False
    used = set()
    for a in d1:
        if a not in used:
            (s1, s2, now) = ({a}, d1[a].copy(), d1[a].copy())
            while now:
                b = now.pop()
                da = d2[b] - s1
                s1 |= da
                for aa in da:
                    db = d1[aa] - s2
                    now |= db
                    s2 |= db
            if len(s1) != len(s2):
                return False
            used |= s1
    return True
(n, m) = RL()
data = []
for _ in range(m):
    data.append(tuple(map(int, sys.stdin.readline().split())))
(l, r) = (min((a[2] for a in data)), max((a[2] for a in data)) + 1)
md = r
last = 0
du = dc(set)
dv = dc(set)
while l < r:
    key = l + r >> 1
    if judge(last, key, du, dv):
        r = key
    else:
        l = key + 1
    last = key
if l >= md:
    print(-1)
else:
    print(l)

Solution (Python):
import os, sys
from io import BytesIO, IOBase

def matching(n, m, path):
    match1 = [-1] * n
    match2 = [-1] * m
    for node in range(n):
        for nei in path[node]:
            if match2[nei] == -1:
                match1[node] = nei
                match2[nei] = node
                break
    while 1:
        bfs = [node for node in range(n) if match1[node] == -1]
        depth = [-1] * n
        for node in bfs:
            depth[node] = 0
        for node in bfs:
            for nei in path[node]:
                next_node = match2[nei]
                if next_node == -1:
                    break
                if depth[next_node] == -1:
                    depth[next_node] = depth[node] + 1
                    bfs.append(next_node)
            else:
                continue
            break
        else:
            break
        pointer = [len(c) for c in path]
        dfs = [node for node in range(n) if depth[node] == 0]
        while dfs:
            node = dfs[-1]
            while pointer[node]:
                pointer[node] -= 1
                nei = path[node][pointer[node]]
                next_node = match2[nei]
                if next_node == -1:
                    while nei != -1:
                        node = dfs.pop()
                        (match2[nei], match1[node], nei) = (node, nei, match1[node])
                    break
                elif depth[node] + 1 == depth[next_node]:
                    dfs.append(next_node)
                    break
            else:
                dfs.pop()
    return match1

def main():
    (n, m) = map(int, input().split())
    edg = [tuple(map(int, input().split())) for _ in range(m)]
    (hi, lo, ans) = (10 ** 9 + 1, 1, 10 ** 9 + 1)
    while hi >= lo:
        mid = (hi + lo) // 2
        path = [[] for _ in range(n)]
        for (a, b, c) in edg:
            if c > mid:
                continue
            path[a - 1].append(b - 1)
        match = matching(n, n, path)
        if not match.count(-1):
            ans = mid
            hi = mid - 1
        else:
            lo = mid + 1
    print(ans if ans != 10 ** 9 + 1 else -1)
BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = 'x' in file.mode or 'r' not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            (self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b'\n') + (not b)
            ptr = self.buffer.tell()
            (self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            (self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode('ascii'))
        self.read = lambda : self.buffer.read().decode('ascii')
        self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
if __name__ == '__main__':
    main()

Solution (Python):
def hopcroft_karp(graph, n, m):
    """"""
    assert n == len(graph)
    match1 = [-1] * n
    match2 = [-1] * m
    for node in range(n):
        for nei in graph[node]:
            if match2[nei] == -1:
                match1[node] = nei
                match2[nei] = node
                break
    while 1:
        bfs = [node for node in range(n) if match1[node] == -1]
        depth = [-1] * n
        for node in bfs:
            depth[node] = 0
        for node in bfs:
            for nei in graph[node]:
                next_node = match2[nei]
                if next_node == -1:
                    break
                if depth[next_node] == -1:
                    depth[next_node] = depth[node] + 1
                    bfs.append(next_node)
            else:
                continue
            break
        else:
            break
        pointer = [len(c) for c in graph]
        dfs = [node for node in range(n) if depth[node] == 0]
        while dfs:
            node = dfs[-1]
            while pointer[node]:
                pointer[node] -= 1
                nei = graph[node][pointer[node]]
                next_node = match2[nei]
                if next_node == -1:
                    while nei != -1:
                        node = dfs.pop()
                        (match2[nei], match1[node], nei) = (node, nei, match1[node])
                    break
                elif depth[node] + 1 == depth[next_node]:
                    dfs.append(next_node)
                    break
            else:
                dfs.pop()
    return (match1, match2)

def getMatchCounts(roads, days, n):
    adj = [[] for _ in range(n)]
    for (u, v, d) in roads:
        if d <= days:
            adj[u].append(v)
    matchCounts = n - hopcroft_karp(adj, n, n)[0].count(-1)
    return matchCounts

def main():
    (n, m) = readIntArr()
    roads = []
    for _ in range(m):
        (u, v, d) = readIntArr()
        u -= 1
        v -= 1
        roads.append([u, v, d])
    if getMatchCounts(roads, 1000000000.0 + 1, n) < n:
        print(-1)
    else:
        days = 0
        b = 1000000000
        while b > 0:
            while getMatchCounts(roads, days + b, n) < n:
                days += b
            b //= 2
        days += 1
        print(days)
    return
import sys
input = sys.stdin.buffer.readline

def oneLineArrayPrint(arr):
    print(' '.join([str(x) for x in arr]))

def multiLineArrayPrint(arr):
    print('\n'.join([str(x) for x in arr]))

def multiLineArrayOfArraysPrint(arr):
    print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))

def readIntArr():
    return [int(x) for x in input().split()]

def makeArr(defaultValFactory, dimensionArr):
    dv = defaultValFactory
    da = dimensionArr
    if len(da) == 1:
        return [dv() for _ in range(da[0])]
    else:
        return [makeArr(dv, da[1:]) for _ in range(da[0])]

def queryInteractive(i, j):
    print('? {} {}'.format(i, j))
    sys.stdout.flush()
    return int(input())

def answerInteractive(ans):
    print('! {}'.format(' '.join([str(x) for x in ans])))
    sys.stdout.flush()
inf = float('inf')
MOD = 10 ** 9 + 7
for _abc in range(1):
    main()