-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathbipartite_matching2.cpp
137 lines (127 loc) · 3.34 KB
/
bipartite_matching2.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
#include <bits/stdc++.h>
using namespace std;
class BipartiteMatching {
int n, n0;
int mode;
vector<vector<int>> adj;
vector<int> mc;
vector<int> used;
bool dfs(int v) {
used[v] = true;
for (int i = 0; i < adj[v].size(); i++) {
int u = adj[v][i];
int w = mc[u];
if (w < 0 || (!used[w] && dfs(w))) {
mc[v] = u;
mc[u] = v;
return true;
}
}
return false;
}
public:
BipartiteMatching(int n) : n(n), adj(n), mc(n, -1) {
mode = 0;
}
BipartiteMatching(int n, int m) : n(n + m), n0(n), adj(n + m), mc(n + m, -1) {
mode = 1;
}
void add_edge(int u, int v) {
if (mode == 0) {
adj[u].push_back(v);
adj[v].push_back(u);
} else {
adj[u].push_back(n0 + v);
adj[n0 + v].push_back(u);
}
}
int match() {
int ret = 0;
for (int v = 0; v < n; v++) {
if (mc[v] < 0) {
used = vector<int>(n);
if (dfs(v)) {
ret++;
}
}
}
return ret;
}
int operator[](int k) {
return mc[k];
}
};
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int t;
cin >> t;
while (t--) {
int n, m;
cin >> n >> m;
vector<vector<int>> adj(n);
for (int i = 1; i < n; i++) {
int p;
cin >> p;
p--;
adj[i].push_back(p);
adj[p].push_back(i);
}
vector<vector<int>> ances(n);
function<void(int, int)> dfs = [&](int v, int p) {
if (p != -1) {
for (int a : ances[p]) ances[v].push_back(a);
}
ances[v].push_back(v);
for (int s : adj[v]) {
if (s != p) {
dfs(s, v);
}
}
};
dfs(0, -1);
for (int i = 0; i < n; i++) {
sort(ances[i].begin(), ances[i].end());
}
vector<vector<int>> lst(m);
for (int i = 0; i < m; i++) {
int k;
cin >> k;
for (int j = 0; j < k; j++) {
int a;
cin >> a;
a--;
lst[i].push_back(a);
}
}
for (int i = 0; i < m; i++) {
sort(lst[i].begin(), lst[i].end());
}
auto ok = [&](int a, int b) {
int i = 0, j = 0;
while (i < ances[a].size() && j < lst[b].size()) {
if (ances[a][i] == lst[b][j]) return true;
if (ances[a][i] < lst[b][j]) i++;
else if (ances[a][i] > lst[b][j]) j++;
}
return false;
};
// for (int i = 0; i < n; i++) {
// cout << "ances[" << i << "]: ";
// for (int a : ances[i]) {
// cout << a << ' ';
// }
// cout << endl;
// }
BipartiteMatching match(n, m);
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (ok(i, j)) {
// cout << "edge: " << i << ' ' << j << endl;
match.add_edge(i, j);
}
}
}
cout << match.match() << endl;
}
}