# 문제 분류
이분 매칭 OR 최대 유량
이분 매칭으로 풀 수도 있다는데 이분 매칭을 몰라서 최대 유량으로 접근했다.
kks227 블로그에 잘 나와있는 것처럼 양쪽에 소스와 싱크를 넣고 해보면 최대 매칭이 가능한 수를 알 수 있다.
#include <algorithm>
#include <cmath>
#include <cstring>
#include <iostream>
#include <queue>
#include <utility>
#include <vector>
#define mp make_pair
#define pb push_back
#define X first
#define Y second
#define fup(i, a, b, c) for (int(i) = (a); (i) <= (b); (i) += (c))
#define fdn(i, a, b, c) for (int(i) = (a); (i) >= (b); (i) -= (c))
#define endl "\n"
using namespace std;
typedef long long ll;
typedef pair<ll, ll> pl;
typedef pair<int, int> pi;
typedef vector<int> vi;
typedef vector<pi> vii;
const ll MOD = 1e9 + 7;
const int stMAX = 1 << 18;
const int INF = 1e9;
int N, M, S = 0, E;
const int MAX_V = 600;
int c[MAX_V][MAX_V], f[MAX_V][MAX_V];
int level[MAX_V], work[MAX_V], total;
vi adj[MAX_V];
bool bfs() {
fill(level, level + MAX_V, -1);
level[S] = 0;
queue<int> Q;
Q.push(S);
while (!Q.empty()) {
int curr = Q.front();
Q.pop();
for (int next : adj[curr]) {
if (level[next] == -1 && c[curr][next] - f[curr][next] > 0) {
level[next] = level[curr] + 1;
Q.push(next);
}
}
}
return level[E] != -1;
}
int dfs(int curr, int dest, int flow) {
if (curr == dest)
return flow;
for (int &i = work[curr]; i < adj[curr].size(); i++) {
int next = adj[curr][i];
if (level[next] == level[curr] + 1 && c[curr][next] - f[curr][next] > 0) {
int df = dfs(next, dest, min(c[curr][next] - f[curr][next], flow));
if (df > 0) {
f[curr][next] += df;
f[next][curr] -= df;
return df;
}
}
}
return 0;
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cin >> N >> M;
E = M + 310;
fup(i, 1, N, 1) {
adj[S].pb(i);
c[S][i] = 1;
}
fup(i, 0, M, 1) {
adj[i + 300].pb(E);
c[i + 300][E] = 1;
}
fup(i, 1, N, 1) {
int u;
cin >> u;
fup(j, 0, u - 1, 1) {
int v;
cin >> v;
adj[i].pb(v + 300);
c[i][v + 300] = 1;
adj[v + 300].pb(i);
c[v + 300][i] = 0;
}
}
while (bfs()) {
fill(work, work + MAX_V, 0);
while (1) {
int flow = dfs(S, E, INF);
if (flow == 0)
break;
total += flow;
}
}
cout << total;
}