結果

問題 No.2403 "Eight" Bridges of Königsberg
ユーザー qwewe
提出日時 2025-05-14 12:47:29
言語 PyPy3
(7.3.15)
結果
WA  
実行時間 -
コード長 1,557 bytes
コンパイル時間 186 ms
コンパイル使用メモリ 82,588 KB
実行使用メモリ 123,956 KB
最終ジャッジ日時 2025-05-14 12:49:24
合計ジャッジ時間 4,454 ms
ジャッジサーバーID
(参考情報)
judge4 / judge1
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 4
other AC * 13 WA * 18
権限があれば一括ダウンロードができます

ソースコード

diff #

import sys
from sys import stdin
sys.setrecursionlimit(1 << 25)

def main():
    import sys
    input = sys.stdin.read
    data = input().split()
    idx = 0
    N = int(data[idx])
    idx +=1
    M = int(data[idx])
    idx +=1
    
    in_degree = [0]*(N+1)
    out_degree = [0]*(N+1)
    
    for _ in range(M):
        u = int(data[idx])
        idx +=1
        v = int(data[idx])
        idx +=1
        out_degree[u] +=1
        in_degree[v] +=1
    
    delta = [0]*(N+1)
    delta_sum = 0
    for i in range(1, N+1):
        delta[i] = out_degree[i] - in_degree[i]
        delta_sum += delta[i]
    
    if delta_sum != 0:
        print(-1)
        return
    
    # Build the undirected graph for connected components
    parent = list(range(N+1))
    
    def find(u):
        while parent[u] != u:
            parent[u] = parent[parent[u]]
            u = parent[u]
        return u
    
    def union(u, v):
        u_root = find(u)
        v_root = find(v)
        if u_root != v_root:
            parent[v_root] = u_root
    
    # Read edges again to build the undirected graph
    idx = 2
    for _ in range(M):
        u = int(data[idx])
        idx +=1
        v = int(data[idx])
        idx +=1
        union(u, v)
    
    # Find connected components
    components = set()
    for i in range(1, N+1):
        components.add(find(i))
    c = len(components)
    
    S = 0
    for i in range(1, N+1):
        if delta[i] > 0:
            S += delta[i]
    
    ans = max(c-1, S-1)
    print(ans)
    
if __name__ == "__main__":
    main()
0