結果

問題 No.416 旅行会社
ユーザー brthyyjpbrthyyjp
提出日時 2020-04-08 04:56:58
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 950 ms / 4,000 ms
コード長 1,765 bytes
コンパイル時間 315 ms
コンパイル使用メモリ 86,676 KB
実行使用メモリ 134,648 KB
最終ジャッジ日時 2023-08-21 10:30:06
合計ジャッジ時間 10,427 ms
ジャッジサーバーID
(参考情報)
judge11 / judge14
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 247 ms
107,204 KB
testcase_01 AC 76 ms
70,928 KB
testcase_02 AC 76 ms
71,140 KB
testcase_03 AC 78 ms
71,344 KB
testcase_04 AC 76 ms
71,472 KB
testcase_05 AC 76 ms
71,300 KB
testcase_06 AC 80 ms
71,564 KB
testcase_07 AC 93 ms
75,392 KB
testcase_08 AC 157 ms
78,984 KB
testcase_09 AC 291 ms
82,312 KB
testcase_10 AC 253 ms
107,188 KB
testcase_11 AC 257 ms
106,944 KB
testcase_12 AC 259 ms
107,172 KB
testcase_13 AC 241 ms
106,968 KB
testcase_14 AC 843 ms
134,616 KB
testcase_15 AC 854 ms
134,536 KB
testcase_16 AC 824 ms
134,648 KB
testcase_17 AC 885 ms
134,268 KB
testcase_18 AC 950 ms
134,532 KB
testcase_19 AC 825 ms
110,688 KB
testcase_20 AC 740 ms
107,868 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

import sys
input = sys.stdin.readline

def Find(x, par):
  if par[x] < 0:
    return x
  else:
    # 経路圧縮
    par[x] = Find(par[x], par)
    return par[x]

def Unite(x, y, par, rank):
  x = Find(x, par)
  y = Find(y, par)

  if x != y:
    # rankの低い方を高い方につなげる
    if rank[x] < rank[y]:
      par[y] += par[x]
      par[x] = y
    else:
      par[x] += par[y]
      par[y] = x
      if rank[x] == rank[y]:
        rank[x] += 1

def Same(x, y, par):
  return Find(x, par) == Find(y, par)

def Size(x, par):
  return -par[Find(x, par)]


n, m, q = map(int, input().split())
AB = []
for i in range(m):
    a, b = map(int, input().split())
    a, b = a-1, b-1
    AB.append((a, b))

CD = []
for i in range(q):
    c, d = map(int, input().split())
    c, d = c-1, d-1
    CD.append((c, d))

S = set(CD)

par = [-1]*n
rank = [0]*n

g = [[] for _ in range(n)]

for i in range(m):
    if AB[i] not in S:
        a, b = AB[i]
        Unite(a, b, par, rank)
        g[a].append(b)
        g[b].append(a)

ans = [0]*n
def dfs(v, p):
    s = [v]
    ans[v] = p
    while s:
        v = s.pop()
        for u in g[v]:
            if ans[u] == 0:
                ans[u] = ans[v]
                s.append(u)

dfs(0, -1)

CD.reverse()
for i in range(q):
    c, d = CD[i]
    if Same(0, c, par) and Same(0, d, par):
        Unite(c, d, par, rank)
    elif  Same(0, c, par) and not Same(0, d, par):
        dfs(d, q-i)
        Unite(c, d, par, rank)
    elif  not Same(0, c, par) and Same(0, d, par):
        dfs(c, q-i)
        Unite(c, d, par, rank)
    else:
        Unite(c, d, par, rank)
        g[c].append(d)
        g[d].append(c)

#for i in range(n):
    #if not Same(0, i, par):
        #ans[i] = 0

for i in range(1, n):
    print(ans[i])
0