結果
問題 |
No.416 旅行会社
|
ユーザー |
|
提出日時 | 2016-10-19 17:24:25 |
言語 | PyPy2 (7.3.15) |
結果 |
TLE
|
実行時間 | - |
コード長 | 1,714 bytes |
コンパイル時間 | 371 ms |
コンパイル使用メモリ | 77,188 KB |
実行使用メモリ | 389,064 KB |
最終ジャッジ日時 | 2024-11-22 16:50:25 |
合計ジャッジ時間 | 55,424 ms |
ジャッジサーバーID (参考情報) |
judge2 / judge4 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
other | AC * 12 TLE * 9 |
ソースコード
import copy class UnionFind(object): def __init__(self, n): self.uf = [-1 for _ in xrange(n)] self.sets = {0:set([0])} def union(self, x, y): x = self.find(x) y = self.find(y) if x == y: return [] if self.uf[x] >= self.uf[y]: if self.uf[x] == self.uf[y] == -1: self.sets[y] = set([x, y]) elif self.uf[x] == -1: self.sets[y].add(x) else: self.sets[y] |= self.sets[x] self.uf[y] += self.uf[x] self.uf[x] = y return self.sets[y] else: if self.uf[y] == -1: self.sets[x].add(y) else: self.sets[x] |= self.sets[y] self.uf[x] += self.uf[y] self.uf[y] = x return self.sets[x] def find(self, x): leaves = [] while self.uf[x] >= 0: leaves.append(x) x = self.uf[x] for lf in leaves: self.uf[lf] = x return x N, M, Q = map(int, raw_input().split()) AB = set([tuple(map(lambda x:int(x)-1, raw_input().split())) for _ in xrange(M)]) CD = [tuple(map(lambda x:int(x)-1, raw_input().split())) for _ in xrange(Q)] AB -= set(CD) uf = UnionFind(N) for a, b in AB: uf.union(a, b) ans = [-1 for _ in xrange(N)] old_set = set(uf.sets[uf.find(0)]) for i in xrange(Q-1, -1, -1): c, d = CD[i] uf.union(c, d) new_set = uf.sets[uf.find(0)] for j in new_set - old_set: ans[j] = i+1 old_set = copy.copy(new_set) for i in xrange(1, N): if ans[i] == -1: print -1 if i in uf.sets[uf.find(0)] else 0 else: print ans[i]