結果

問題 No.2403 "Eight" Bridges of Königsberg
ユーザー ニックネームニックネーム
提出日時 2023-08-04 22:23:28
言語 Python3
(3.13.1 + numpy 2.2.1 + scipy 1.14.1)
結果
AC  
実行時間 699 ms / 2,000 ms
コード長 738 bytes
コンパイル時間 328 ms
コンパイル使用メモリ 12,672 KB
実行使用メモリ 26,496 KB
最終ジャッジ日時 2024-11-26 17:48:52
合計ジャッジ時間 8,649 ms
ジャッジサーバーID
(参考情報)
judge5 / judge1
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 4
other AC * 31
権限があれば一括ダウンロードができます

ソースコード

diff #

class UF:
    def __init__(self,n):
        self.p = [-1]*n
    def f(self,x):
        if self.p[x]<0: return x
        else: self.p[x] = self.f(self.p[x]); return self.p[x]
    def u(self,x,y):
        x = self.f(x); y = self.f(y)
        if x==y: return
        if -self.p[x]<-self.p[y]: x,y = y,x
        self.p[x] += self.p[y]; self.p[y] = x
n,m = map(int,input().split())
a = [0]*n; b = [0]*n; c = [[] for _ in range(n)]; uf = UF(n)
for _ in range(m):
    u,v = map(int,input().split())
    a[u-1] += 1; b[v-1] += 1; uf.u(u-1,v-1)
for i,(u,v) in enumerate(zip(a,b)):
    if u>v or u==v>0: c[uf.f(i)].append(u-v)
d = p = q = 0
for i in range(n):
    if c[i]:
        d += sum(c[i]); p += 1
        if sum(c[i])==0: q += 1
print(d+q-1)
0