結果

問題 No.1553 Lovely City
ユーザー convexineq
提出日時 2021-06-18 22:49:41
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 677 ms / 2,000 ms
コード長 1,921 bytes
コンパイル時間 508 ms
コンパイル使用メモリ 82,472 KB
実行使用メモリ 137,976 KB
最終ジャッジ日時 2024-06-22 21:09:53
合計ジャッジ時間 17,357 ms
ジャッジサーバーID
(参考情報)
judge1 / judge5
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 2
other AC * 26
権限があれば一括ダウンロードができます

ソースコード

diff #

class UnionFind:
    def __init__(self, n):
        self.parent = list(range(n)) #親ノード
        self.size = [1]*n #グループの要素数
 
    def root(self, x): #root(x): xの根ノードを返す.
        while self.parent[x] != x:
            self.parent[x] = self.parent[self.parent[x]]
            x = self.parent[x]
        return x 
 
    def merge(self, x, y): #merge(x,y): xのいる組とyのいる組をまとめる
        x, y = self.root(x), self.root(y)
        if x == y: return False
        if self.size[x] < self.size[y]: x,y=y,x #xの要素数が大きいように
        self.size[x] += self.size[y] #xの要素数を更新
        self.parent[y] = x #yをxにつなぐ
        return True
 
    def issame(self, x, y): #same(x,y): xとyが同じ組ならTrue
        return self.root(x) == self.root(y)
        
    def getsize(self,x): #size(x): xのいるグループの要素数を返す
        return self.size[self.root(x)]

import sys
readline = sys.stdin.readline

n,m = map(int,readline().split())
g = [[] for _ in range(n)]

UF = UnionFind(n+1)
g = [[] for _ in range(n+1)]
ind = [0]*(n+1)

for _ in range(m):
    a,b = map(int,readline().split())
    g[a].append(b)
    ind[b] += 1
    UF.merge(a,b)

from collections import defaultdict
d = defaultdict(list)
for i in range(1,n+1):
    r = UF.root(i)
    d[r].append(i)

def top_sort(lst):
    q = [i for i in lst if ind[i]==0]
    res = []
    while q:
        v = q.pop()
        res.append(v)
        for c in g[v]:
            ind[c] -= 1
            if ind[c] == 0:
                q.append(c)
    return res

ans = []
for r,lst in d.items():
    ts = top_sort(lst)
    if len(ts) == len(lst):
        for i,j in zip(ts,ts[1:]):
            ans.append((i,j))
    else:
        for i,j in zip(lst,lst[1:]):
            ans.append((i,j))
        ans.append((lst[-1],lst[0]))

print(len(ans))
for i,j in ans:
    print(i,j)
0