結果
| 問題 |
No.1553 Lovely City
|
| コンテスト | |
| ユーザー |
ygd.
|
| 提出日時 | 2021-06-18 22:54:36 |
| 言語 | Python3 (3.13.1 + numpy 2.2.1 + scipy 1.14.1) |
| 結果 |
WA
|
| 実行時間 | - |
| コード長 | 3,803 bytes |
| コンパイル時間 | 128 ms |
| コンパイル使用メモリ | 13,184 KB |
| 実行使用メモリ | 164,124 KB |
| 最終ジャッジ日時 | 2024-06-22 21:13:06 |
| 合計ジャッジ時間 | 33,372 ms |
|
ジャッジサーバーID (参考情報) |
judge4 / judge1 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 2 |
| other | AC * 2 WA * 14 TLE * 10 |
ソースコード
import sys
sys.setrecursionlimit(10**7)
from collections import defaultdict
class UnionFind(object):
def __init__(self, n=1):
self.par = [i for i in range(n)]
self.rank = [0 for _ in range(n)]
self.size = [1 for _ in range(n)]
def find(self, x):
"""
x が属するグループを探索して親を出す。
"""
if self.par[x] == x:
return x
else:
self.par[x] = self.find(self.par[x])
return self.par[x]
def union(self, x, y):
"""
x と y のグループを結合
"""
x = self.find(x)
y = self.find(y)
if x != y:
if self.rank[x] < self.rank[y]:
x, y = y, x
if self.rank[x] == self.rank[y]:
self.rank[x] += 1
self.par[y] = x
self.size[x] += self.size[y]
def is_same(self, x, y):
"""
x と y が同じグループか否か
"""
return self.find(x) == self.find(y)
def get_size(self, x):
"""
x が属するグループの要素数
"""
x = self.find(x)
return self.size[x]
def SCC(N, G, RG):
order = []
used = [0]*N
group = [None]*N
def dfs(s):
used[s] = 1
for t in G[s]:
if not used[t]:
dfs(t)
order.append(s)
def rdfs(s, col):
#print(s)
group[s] = col
used[s] = 1
for t in RG[s]:
if not used[t]:
rdfs(t, col)
TS.append(s)
for i in range(N):
if not used[i]:
dfs(i)
used = [0]*N
label = 0
TSL = []
for s in reversed(order):
if not used[s]:
TS = []
rdfs(s, label)
#TS.reverse()
TSL.append(TS)
label += 1
return label, group, TSL
def main():
N,M = map(int,input().split())
Q = []
S = set([])
for i in range(M):
U,V = map(int,input().split())
Q.append((U,V))
S.add(U)
S.add(V)
L = list(S)
n = len(S) #出てくる頂点の種類
L.sort()
dic = {} #元の番号→座圧後の番号
revdic = {} #座圧後の番号→元の番号
for i in range(n):
dic[L[i]] = i
revdic[i] = L[i]
ALL = [i for i in range(n)]
ALL = set(ALL)
G = [[] for _ in range(n)]
RG = [[] for _ in range(n)]
uf = UnionFind(n)
for u,v in Q:
uz = dic[u]
vz = dic[v]
G[uz].append(vz)
RG[vz].append(uz)
uf.union(uz,vz)
#print(G)
unidic = defaultdict(list)
for i in range(n):
par = uf.find(i)
unidic[par].append(i)
#print(unidic)
#連結成分ごとにSCC
ans = []
#for L in unidic.values():
LIST, Group, TT = SCC(n, G, RG)
#print(LIST,Group,TT)
prepar = -1
for i,group in enumerate(TT):
nowpar = uf.find(group[0])
#print(i,prepar,nowpar)
if i != 0 and prepar == nowpar: #一番初めではないし、今見てる塊が前とつながっている。
pre = TT[i-1][0]
oripre = revdic[pre]
first = group[0]
orifirst = revdic[first]
ans.append([oripre, orifirst])
else:
prepar = nowpar
if len(group) == 1: continue #一つだったらつなげる必要なし
for j in range(len(group)):
if j < len(group) - 1:
s = group[j]; t = group[j+1]
else:
s = group[j]; t = group[0]
oris = revdic[s]; orit = revdic[t]
ans.append([oris, orit])
print(len(ans))
for ret in ans:
print(*ret)
if __name__ == '__main__':
main()
ygd.