結果

問題 No.2531 Coloring Vertices on Namori
ユーザー LyricalMaestro
提出日時 2024-09-28 01:43:30
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 644 ms / 2,000 ms
コード長 1,303 bytes
コンパイル時間 229 ms
コンパイル使用メモリ 82,380 KB
実行使用メモリ 155,368 KB
最終ジャッジ日時 2024-09-28 01:43:47
合計ジャッジ時間 16,289 ms
ジャッジサーバーID
(参考情報)
judge4 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 31
権限があれば一括ダウンロードができます

ソースコード

diff #

## https://yukicoder.me/problems/no/2531

MOD = 998244353

from collections import deque


def main():
    N, K = map(int, input().split())
    next_nodes = [set() for _ in range(N)]
    for _ in range(N):
        u,v = map(int, input().split())
        next_nodes[u - 1].add(v - 1)
        next_nodes[v - 1].add(u - 1)


    queue= deque()
    for i in range(N):
        if len(next_nodes[i]) == 1:
            queue.append(i)
        
    while len(queue) > 0:
        i = queue.popleft()
        for j in next_nodes[i]:
            next_nodes[j].remove(i)
            if len(next_nodes[j]) == 1:
                queue.append(j)
        
        next_nodes[i].clear()

    # 巡回になっている大きさをカウント
    cnt = 0
    for i in range(N):
        if len(next_nodes[i]) > 0:
            cnt += 1

    # どう的計画法を使って計算
    dp = [[0, 0] for _ in range(cnt)]
    dp[0][0] = 1
    for i in range(1, cnt):
        dp[i][1] += ((K - 2) * dp[i - 1][1]) % MOD
        dp[i][1] %= MOD
        dp[i][1] += ((K - 1) * dp[i - 1][0]) % MOD
        dp[i][1] %= MOD

        dp[i][0] = dp[i - 1][1]
    
    ans = dp[-1][1]
    ans *= K
    ans %= MOD

    n = N - cnt
    ans *= pow(K - 1, n, MOD)
    ans %= MOD
    print(ans)









if __name__ == "__main__":
    main()
0