Valuable Paper (Codeforces 1424B)
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):
from collections import defaultdict
(n, k) = map(int, input().split())
ma = 0
a = []
graph = []
factories = 0
ports = 0
f = [False] * (n + 1)
p = [False] * (n + 1)
for i in range(k):
    (u, v, d) = map(int, input().split())
    graph.append([u, v, d])
    ma = max(ma, d)
s = 0
l = ma
ans = -1
while s <= l:
    m = (s + l) // 2
    factories = 0
    ports = 0
    f = defaultdict(bool)
    p = defaultdict(bool)
    for i in range(k):
        (u, v, d) = graph[i]
        if d <= m:
            if not f[u]:
                f[u] = True
                factories += 1
            if not p[v]:
                p[v] = True
                ports += 1
    if factories == n and ports == n:
        ans = m
        l = m - 1
    else:
        s = m + 1
print(ans)

Solution (Python):
""""""
from os import path
import sys
from heapq import heappush, heappop
from functools import cmp_to_key as ctk
from collections import deque, defaultdict as dd
from bisect import bisect, bisect_left, bisect_right, insort, insort_left, insort_right
from itertools import permutations
from datetime import datetime
from math import ceil, sqrt, log, gcd

def ii():
    return int(input())

def si():
    return input().rstrip()

def mi():
    return map(int, input().split())

def li():
    return list(mi())
abc = 'abcdefghijklmnopqrstuvwxyz'
mod = 998244353
inf = float('inf')
vow = ['a', 'e', 'i', 'o', 'u']
(dx, dy) = ([-1, 1, 0, 0], [0, 0, 1, -1])

def bo(i):
    return ord(i) - ord('a')

def solve():
    (n, m1) = mi()
    a = []
    for i in range(m1):
        a.append(li())

    def check(ti):
        deg = [0] * (n + 1)
        deg1 = [0] * (n + 1)
        for i in range(m1):
            if a[i][2] <= ti:
                deg[a[i][0]] += 1
                deg1[a[i][1]] += 1
        for i in range(1, n + 1):
            if deg[i] == 0 or deg1[i] == 0:
                return 0
        return 1
    l = 1
    r = 10 ** 9
    ans = -1
    while l <= r:
        m = l + (r - l) // 2
        if check(m):
            ans = m
            r = m - 1
        else:
            l = m + 1
    print(ans)
if __name__ == '__main__':
    if path.exists('input.txt'):
        sys.stdin = open('input.txt', 'r')
        sys.stdout = open('output.txt', 'w')
    else:
        input = sys.stdin.readline
    solve()

Solution (Python):
from bisect import bisect_left as bl
from bisect import bisect_right as br
from heapq import heappush, heappop, heapify
import math
from collections import *
from functools import reduce, cmp_to_key
import sys
input = sys.stdin.readline
from itertools import accumulate
from functools import lru_cache
M = mod = 10 ** 9 + 7

def factors(n):
    return sorted(set(reduce(list.__add__, ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0))))

def inv_mod(n):
    return pow(n, mod - 2, mod)

def li():
    return [int(i) for i in input().rstrip('\n').split()]

def st():
    return input().rstrip('\n')

def val():
    return int(input().rstrip('\n'))

def li2():
    return [i for i in input().rstrip('\n')]

def li3():
    return [int(i) for i in input().rstrip('\n')]
graph = defaultdict(dict)
(n, m) = li()
l = []
for j in range(m):
    (u, v, d) = li()
    l.append([u, v, d])
l.sort(key=lambda x: x[-1])

def check(weight):
    airports = set()
    factoris = set()
    for i in l:
        if i[-1] <= weight:
            airports.add(i[0])
            factoris.add(i[1])
        else:
            break
    return 1 if len(factoris) == len(airports) and len(factoris) == n else 0
low = 1
high = 10 ** 9
ans = 10 ** 10
while low <= high:
    mid = low + high >> 1
    if check(mid):
        ans = min(ans, mid)
        high = mid - 1
    else:
        low = mid + 1
if ans == 10 ** 10:
    print(-1)
    exit()
print(ans)