結果
| 問題 |
No.1553 Lovely City
|
| コンテスト | |
| ユーザー |
|
| 提出日時 | 2021-06-19 15:50:03 |
| 言語 | PyPy3 (7.3.15) |
| 結果 |
WA
|
| 実行時間 | - |
| コード長 | 1,954 bytes |
| コンパイル時間 | 320 ms |
| コンパイル使用メモリ | 82,264 KB |
| 実行使用メモリ | 139,148 KB |
| 最終ジャッジ日時 | 2024-06-22 22:06:44 |
| 合計ジャッジ時間 | 19,033 ms |
|
ジャッジサーバーID (参考情報) |
judge3 / judge4 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 2 |
| other | AC * 4 WA * 22 |
ソースコード
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 = []
dis = [n+5]*(n+1)
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)
dis[ind] = 0
if len(q) == 0:
for j in range(len(group[i])):
x = group[j]
y = group[(j+1)%len(group[i])]
ans.append((x,y))
continue
order = []
while q:
now = q.pop()
order.append(now)
for nex in e[now]:
deg[nex] -= 1
if deg[nex] == 0:
q.append(nex)
dis[nex] = dis[now]+1
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[j]
y = group[(j+1)%len(group[i])]
ans.append((x,y))
print(len(ans))
for x,y in ans:
print(x,y)