Table of Contents

SolutionImplementation

Solution

If we define dp[S]\texttt{dp}[S] to be the number of matchings for females in the set SS to the first S|S| males, this problem boils down to the following:

dp[S]=dp[S\x]:compatible[S][x]\texttt{dp}[S] = \sum \texttt{dp}[S\backslash x]: \texttt{compatible}[|S|][x]

(The : stands for "such that".) In English, this is equivalent to the following:

The number of matchings in a subset SS to include a certain female xx is equivalent to the sum of all the matchings without female xx where female xx is compatible with the S|S|-th male.

Our base case is the empty set, which has a value of 11 (the empty set can be considered as a single matching involving zero pairs).

Implementation

Time Complexity: O(N2N)\mathcal{O}(N\cdot 2^N)

MOD = 10**9 + 7
MAX_N = 21
n = int(input())
compat = []
for _ in range(n):
compat.append(list(map(int, input().split())))
dp = [0] * (1 << n)

Join the USACO Forum!

Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!