---
id: 1199
lang: en
translation_of: index.md
source_sha256: 86ddbdbbf0108d13441f2f5df54442513e223b72d87d0fd867a5f9dfdef511e6
title: "Educational DP Contest: O – Matching — Solution"
description: "The constraints suggest bitmask DP: dp[S] counts the transitions for the set S of women matched to the first |S| men."
tags: ["OI","DP","Bitmask DP"]
translated: 2026-11-27
translator: Claude Opus 5.5
translator_model: claude-opus-5-5
translation_notes: []
---

## Solution

Looking at the constraints of this problem, you can think of bitmask $DP$. Consider designing a state: $dp[S]$ represents a set of women, where the size of the set $|S|$ provides another piece of information. In other words, $dp[S]$ represents the number of transitions for the set of women corresponding to the first $|S|$ men. It is not hard to derive the following formula:

$$
dp[S] = \sum_{(i, |S|) \in compatible} dp[S'], S' \cup i = S
$$

<!--more-->

## Code

```cpp
// O.cpp
#include <bits/stdc++.h>
using namespace std;
const int MAX_N = 22, mod = 1e9 + 7;

int n, dp[1 << MAX_N], tmp;
bool mapping[MAX_N][MAX_N];

int main()
{
    scanf("%d", &n);
    for (int i = 1; i <= n; i++)
        for (int j = 1; j <= n; j++)
            scanf("%d", &tmp), mapping[i][j] = (tmp == 1);
    dp[0] = 1;
    for (int i = 1; i < (1 << n); i++)
    {
        int counter = 0;
        for (int j = 0; j < n; j++)
            if ((i >> j) & 1)
                counter++;
        for (int j = 0; j < n; j++)
            if (((i >> j) & 1) && mapping[counter][j + 1])
                dp[i] = (dp[i] + dp[i ^ (1 << j)]) % mod;
    }
    printf("%d", dp[(1 << n) - 1]);
    return 0;
}
```
