problems / 268

On-Call Rotation Matching

medium graphs bipartite dfs flow 1000 ms · 256 MB

On-Call Rotation Matching

Your team is filling next month's on-call rotation. There are n engineers, numbered from 1 to n, and m on-call shifts, numbered from 1 to m. Not everyone can cover every shift: each engineer has a list of shifts they are qualified for (the right timezone, the right service knowledge, no planned leave).

To keep the load fair, each engineer is given at most one shift, and each shift is given to at most one engineer. An engineer may only be given a shift from their own list. Some engineers may end up with no shift, and some shifts may stay uncovered.

What is the largest number of shifts that can be covered at the same time?

Input

The first line contains two integers n and m (1 ≤ n ≤ 500, 1 ≤ m ≤ 500): the number of engineers and the number of shifts.

Each of the next n lines describes one engineer, in order from engineer 1 to engineer n. The line starts with an integer k_i (0 ≤ k_i ≤ m), the number of shifts engineer i is qualified for, followed by k_i pairwise distinct integers s_1, s_2, …, s_{k_i} (1 ≤ s_j ≤ m): those shifts, in no particular order.

The total number of qualifications over all engineers is at most 10^5 (k_1 + k_2 + … + k_n ≤ 10^5).

Output

Print one integer: the maximum number of shifts that can be covered.

Notes

In the first example, giving engineer 1 shift 1 looks natural, but then engineer 2 (who can only take shift 1) is left out. Instead, engineer 1 takes shift 2, engineer 2 takes shift 1 and engineer 3 takes shift 3, covering all three shifts.

In the second example, engineer 1 is not qualified for anything, and engineers 2 and 3 both want only shift 2, so at most one of them gets it. Engineer 4 covers shift 1 or shift 3, for a total of 2.

Example 1

Input

3 3
2 1 2
1 1
2 2 3

Output

3

Example 2

Input

4 3
0
1 2
1 2
2 1 3

Output

2

Hints · reveal one at a time if you're stuck

Hint 1

Greedy choices fail: in the first example, giving engineer 1 shift 1 blocks engineer 2. Instead of committing forever, can an earlier decision be revised when a new engineer arrives?

Hint 2

When engineer e finds all their shifts taken, try to move the owner of one of those shifts to another shift the owner is qualified for, and so on, until some chain ends at a free shift. Each such successful chain increases the number of covered shifts by one.

Hint 3

Engineers and shifts form a bipartite graph and the answer is its maximum matching. Kuhn's augmenting-path DFS (or the faster Hopcroft–Karp algorithm) finds it.

report an issue Prefer your own editor? sooks prep 268 (CLI)
Sign in to run code

Run your code on the examples, or submit it against every test.