結果
| 問題 |
No.1553 Lovely City
|
| コンテスト | |
| ユーザー |
|
| 提出日時 | 2021-06-19 15:53:27 |
| 言語 | PyPy3 (7.3.15) |
| 結果 |
AC
|
| 実行時間 | 834 ms / 2,000 ms |
| コード長 | 1,709 bytes |
| コンパイル時間 | 383 ms |
| コンパイル使用メモリ | 82,424 KB |
| 実行使用メモリ | 137,428 KB |
| 最終ジャッジ日時 | 2024-06-22 22:07:07 |
| 合計ジャッジ時間 | 19,721 ms |
|
ジャッジサーバーID (参考情報) |
judge1 / judge2 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 2 |
| other | AC * 26 |
ソースコード
from collections import deque
class Unionfind:
def __init__(self,n):
self.uf = [-1]*n
def find(self,x):
if self.uf[x] < 0:
return x
else:
self.uf[x] = self.find(self.uf[x])
return self.uf[x]
def same(self,x,y):
return self.find(x) == self.find(y)
def union(self,x,y):
x = self.find(x)
y = self.find(y)
if x == y:
return False
if self.uf[x] > self.uf[y]:
x,y = y,x
self.uf[x] += self.uf[y]
self.uf[y] = x
return True
def size(self,x):
x = self.find(x)
return -self.uf[x]
n,m = map(int,input().split())
uf = Unionfind(n+1)
e = [[] for i in range(n+1)]
deg = [0]*(n+1)
use = [0]*(n+1)
for _ in range(m):
u,v = map(int,input().split())
e[u].append(v)
uf.union(u,v)
use[u] = 1
use[v] = 1
deg[v] += 1
group = [[] for i in range(n+1)]
for i in range(n+1):
if use[i]:
group[uf.find(i)].append(i)
ans = []
for i in range(n+1):
if group[i] == []:
continue
q = deque([])
loop = 0
for ind in group[i]:
if deg[ind]:
continue
q.append(ind)
order = []
while q:
now = q.pop()
order.append(now)
for nex in e[now]:
deg[nex] -= 1
if deg[nex] == 0:
q.append(nex)
if len(order) == len(group[i]):
for x,y in zip(order,order[1:]):
ans.append((x,y))
else:
for j in range(len(group[i])):
x = group[i][j]
y = group[i][(j+1)%len(group[i])]
ans.append((x,y))
print(len(ans))
for x,y in ans:
print(x,y)