-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhopmancroftmatching.cpp
126 lines (111 loc) · 2.66 KB
/
hopmancroftmatching.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
#include <bits/stdc++.h>
using namespace std;
#define MAX 100010
#define clr(ar) memset(ar, 0, sizeof(ar))
#define read() freopen("lol.txt", "r", stdin)
#define dbg(x) cout << #x << " = " << x << endl
#define ran(a, b) ((((rand() << 15) ^ rand()) % ((b) - (a) + 1)) + (a))
typedef pair<string,string> pss;
/// Hopcroft karp in O(m * sqrt(n))
namespace hc{ /// hash = 393558
bool visited[MAX];
vector <int> adj[MAX];
int n, L[MAX], R[MAX], Q[MAX], len[MAX], dis[MAX], parent[MAX];
inline void init(int nodes){ /// Number of vertices in the left set, or max(left_set, right_set)
n = nodes, clr(len);
for (int i = 0; i < MAX; i++) adj[i].clear();
}
inline void add_edge(int u, int v){ /// 0 based index
len[u]++;
adj[u].push_back(v);
}
bool dfs(int i){
for (int j = 0; j < len[i]; j++){
int x = adj[i][j];
if (L[x] == -1 || (parent[L[x]] == i)){
if (L[x] == -1 || dfs(L[x])){
L[x] = i, R[i] = x;
return true;
}
}
}
return false;
}
bool bfs(){
clr(visited);
int i, j, x, d, f = 0, l = 0;
for (i = 0; i < n; i++){
if (R[i] == -1){
visited[i] = true;
Q[l++] = i, dis[i] = 0;
}
}
while (f < l){
i = Q[f++];
for (j = 0; j < len[i]; j++){
x = adj[i][j], d = L[x];
if (d == -1) return true;
else if (!visited[d]){
Q[l++] = d;
parent[d] = i, visited[d] = true, dis[d] = dis[i] + 1;
}
}
}
return false;
}
int hopcroft_karp(){
int res = 0;
memset(L, -1, sizeof(L));
memset(R, -1, sizeof(R));
while (bfs()){
for (int i = 0; i < n; i++){
if (R[i] == -1 && dfs(i)) res++;
}
}
return res;
}
void pp(int x)
{
for(int i=0;i<=x;i++)
{
cout<<R[i]<<" "<<L[R[i]]<<endl;
}
}
}
vector<pss> votes;
void solve(int t)
{
votes.clear();
int n,m,f;
string s1,s2;
scanf("%d %d %d",&f,&m,&n);
for(int i=0;i<n;i++)
{
cin>>s1>>s2;
votes.push_back(pss(s1,s2));
}
hc::init(max(n, m)+50);
for(int i=0;i<n;i++)
{
pss u=votes[i];
if(u.first[0]=='F') continue;
for(int j=0;j<n;j++)
{
pss v=votes[j];
if(u.first==v.second || u.second==v.first)
{
hc::add_edge(i,j);
}
}
}
printf("Case %d: %d\n", t,n-hc::hopcroft_karp());
}
int main(){
int t;
cin>>t;
for(int i=0;i<t;i++)
{
solve(i+1);
}
return 0;
}