ABC310D - Peaceful Teams

考え方

Editorial - freee Programming Contest 2023(AtCoder Beginner Contest 310)


回答例

PyPy3 (7.3.0)だと間に合う.Python (3.8.2)だとTLE.

from copy import deepcopy
N, T, M = map(int, input().split())
G = [set() for _ in range(N)]
for _ in range(M):
    a, b = map(int, input().split())
    a -= 1
    b -= 1
    G[a].add(b)
    G[b].add(a)

def f(i, team):
    global ans
    if i == N - 1:
        if len(team) == T:
            ans += 1
        return
    for j in range(len(team)):
        if team[j] & G[i + 1]:continue
        tmp = deepcopy(team)
        tmp[j].add(i+1)
        f(i + 1, tmp)
    if len(team) < T:
        f(i + 1, team + [set([i + 1])])

ans = 0
f(0, [set([0])])
print(ans)