-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaximum Bipartite Matching.cpp
More file actions
150 lines (125 loc) · 2.86 KB
/
Maximum Bipartite Matching.cpp
File metadata and controls
150 lines (125 loc) · 2.86 KB
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
138
139
140
141
142
143
144
145
146
147
148
149
150
#include <bits/stdc++.h>
#define lli long long int
#define endl "\n"
#define debug(n) cout<<n<<endl
#define debug2(a, b) cout<<a<<" "<<b<<endl;
#define forn(i, in, fin) for(int i = in; i<fin; i++)
#define all(v) v.begin(), v.end()
#define fastIO(); ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
using namespace std;
const lli INF = numeric_limits<int>::max();
struct Edge
{
lli to, flow, capacity;
Edge* res;
Edge(lli to, lli flow, lli capacity): to(to), flow(flow), capacity(capacity) {}
void addFlow(lli flow)
{
this->flow += flow;
this->res->flow -= flow;
}
};
vector< vector<Edge*> > adjList;
vector<lli> dis;
vector<lli> pos;
void addEdge(lli u, lli v, lli capacity)
{
Edge* uv = new Edge(v, 0, capacity);
Edge* vu = new Edge(u, 0, 0);
uv->res = vu;
vu->res = uv;
adjList[u].push_back(uv);
adjList[v].push_back(vu);
}
lli blockingFlow(lli u, lli t, lli flow)
{
if(u==t) return flow;
for(lli &i = pos[u]; i<adjList[u].size(); i++)
{
Edge* v = adjList[u][i];
if(v->capacity > v->flow && dis[u] + 1 == dis[v->to])
{
lli fv = blockingFlow(v->to, t, min(flow, v->capacity - v->flow));
if(fv>0)
{
v->addFlow(fv);
return fv;
}
}
}
return 0;
}
lli dinic(lli s, lli t)
{
lli maxFlow = 0;
dis[t] = 0;
while(dis[t] != -1)
{
fill(all(dis), -1);
queue<lli> q;
q.push(s);
dis[s] = 0;
while(!q.empty())
{
lli u = q.front(); q.pop();
for(Edge* v: adjList[u])
{
if(dis[v->to] == -1 && v->capacity > v->flow)
{
dis[v->to] = dis[u] + 1;
q.push(v->to);
}
}
}
if(dis[t] != -1)
{
lli f = 0;
fill(all(pos), 0);
while( f = blockingFlow(s,t,INF))
{
maxFlow += f;
}
}
}
return maxFlow;
}
void solve()
{
lli m, n; cin>>m>>n;
adjList.clear();
adjList.resize(n+m+2);
dis.clear();
dis.resize(n+m+2);
pos.clear();
pos.resize(n+m+2);
for(int i = 1; i<=m; i++)
{
for(int j = 1; j<=n; j++)
{
lli a; cin>>a;
if(a)
{
addEdge(j, i+n , 1);
}
}
}
for(int i = 1; i<=n; i++)
{
addEdge(0, i, 1);
}
for(int i = 1; i<=m; i++)
{
addEdge(i+n, 1+n+m, 1);
}
cout<<dinic(0, 1+n+m)<<endl;
}
int main()
{
fastIO();
lli t; cin>>t;
while(t--)
{
solve();
}
return 0;
}