結果

問題 No.196 典型DP (1)
ユーザー neterukun
提出日時 2019-12-31 00:52:35
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 208 ms / 2,000 ms
コード長 1,316 bytes
コンパイル時間 331 ms
コンパイル使用メモリ 82,032 KB
実行使用メモリ 110,336 KB
最終ジャッジ日時 2024-11-16 10:18:34
合計ジャッジ時間 6,916 ms
ジャッジサーバーID
(参考情報)
judge3 / judge4
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 41
権限があれば一括ダウンロードができます

ソースコード

diff #

import sys
sys.setrecursionlimit(10**6)


n, k = map(int, input().split())
info = [list(map(int, input().split())) for i in range(n-1)]
MOD = 10**9 + 7

tree = [[] for i in range(n)]
for i in range(n-1):
    tree[info[i][0]].append(info[i][1])
    tree[info[i][1]].append(info[i][0])

dp = [[0]*(n+1) for i in range(n)]

cnt_v = [1] *n
def solve(prev_pos, pos):
    # dfsで辺を葉の方向へと辿る
    for next_pos in tree[pos]:
        if prev_pos == next_pos:
            continue
        solve(pos, next_pos)
    
    # 頂点posに対して、next_posを根とする部分木をマージしていく
    dp[pos][0] = 1
    for next_pos in tree[pos]:
        if prev_pos == next_pos:
            continue
        
        tmp = [0] * (cnt_v[pos] + cnt_v[next_pos] + 1)
        # マージされる側に存在する辺の本数
        for i in range(cnt_v[pos] + 1):
            # マージする側に存在する辺の本数
            for j in range(cnt_v[next_pos] + 1):
                # マージの内容
                tmp[i+j] += dp[pos][i] * dp[next_pos][j]
                tmp[i+j] %= MOD

        cnt_v[pos] += cnt_v[next_pos]
        for j in range(cnt_v[pos]+1):
            dp[pos][j] = tmp[j]
            dp[pos][j] %= MOD
    dp[pos][cnt_v[pos]] = 1

solve(-1, 0)
print(dp[0][k] % MOD)
0