33062023-02-24 19:31:3312BotiHírvivők csoportosítása (40)python3Accepted 40/40218ms41344 KiB
N, M, H, K = map(int, input().split())
hs = [tuple(map(int, input().split())) for _ in range(H)]

# counting sort of edges, we can afford O(n^2)
edges = [[] for _ in range(20000)]
for i in range(H):
    for j in range(i + 1, H):
        dist = abs(hs[i][0] - hs[j][0]) + abs(hs[i][1] - hs[j][1])
        edges[dist].append((i, j))

# https://en.wikipedia.org/wiki/Disjoint-set_data_structure
par = list(range(H))
rank = [0] * H
count = H

def find(a):
    while par[a] != a:
        # path halving
        par[a] = par[par[a]]
        a = par[a]
    return a

def union(a, b):
    global count
    a = find(a)
    b = find(b)
    if a == b:
        return
    count -= 1
    # merge by rank
    if rank[a] == rank[b]:
        par[b] = a
        rank[a] += 1
    elif rank[a] > rank[b]:
        par[b] = a
    else:
        par[a] = b

for dist, es in enumerate(edges):
    for a, b in es:
        union(a, b)
    if count <= K:
        print(dist)
        exit()
SubtaskSumTestVerdictTimeMemory
base40/40
1Accepted0/026ms14400 KiB
2Accepted0/0142ms34360 KiB
3Accepted1/129ms15996 KiB
4Accepted1/126ms15428 KiB
5Accepted1/146ms18592 KiB
6Accepted1/145ms18812 KiB
7Accepted1/132ms16648 KiB
8Accepted1/129ms16816 KiB
9Accepted1/130ms16720 KiB
10Accepted1/146ms19088 KiB
11Accepted1/145ms19300 KiB
12Accepted1/146ms19348 KiB
13Accepted3/3202ms40168 KiB
14Accepted3/3210ms40152 KiB
15Accepted3/3201ms40284 KiB
16Accepted3/3195ms40488 KiB
17Accepted3/3200ms40428 KiB
18Accepted3/3194ms40704 KiB
19Accepted3/3218ms40956 KiB
20Accepted3/3206ms41212 KiB
21Accepted3/3196ms41344 KiB
22Accepted3/3194ms41124 KiB