Pagini recente » Cod sursa (job #2560245) | Cod sursa (job #2689647)
#include <bits/stdc++.h>
using namespace std;
struct Graph{
int l, r, n, s, d;
vector < vector <int> > graph;
vector < vector <int> > cap;
vector <int> pr;
Graph(int _l, int _r): l(_l), r(_r), n(l + r + 2),
s(0), d(n - 1), graph(n), cap(n, vector<int>(n)), pr(n) {
for (int i = 1; i <= l; ++i)
AddEdge(s, i);
for (int i = l + 1; i <= l + r; ++i)
AddEdge(i, d);
}
void AddEdge(int a, int b){
graph[a].push_back(b);
graph[b].push_back(a);
cap[a][b] = 1;
}
bool bfs(){
queue <int> Q;
fill(pr.begin(), pr.end(), 1e9);
Q.push(s);
pr[s] = -1;
while (not Q.empty()){
int node = Q.front();
Q.pop();
for (int nei : graph[node]){
if (pr[nei] == 1e9 && cap[node][nei]){
pr[nei] = node;
Q.push(nei);
}
}
}
return (pr[d] != 1e9);
}
vector < pair <int, int> > maxFlow(vector < pair <int, int> >& edges){
int maxFlow = 0;
while (bfs()){
int flow = 1e9;
for (int node = d; node != s; node = pr[node])
flow = min(flow, cap[pr[node]][node]);
for (int node = d; node != s; node = pr[node]){
cap[pr[node]][node] -= flow;
cap[node][pr[node]] += flow;
}
maxFlow += flow;
}
vector < pair <int, int> > ans;
for (auto& it: edges){
int a = it.first;
int b = it.second;
if (!cap[a][b])
ans.push_back(it);
}
assert(maxFlow == (int) ans.size());
return ans;
}
};
int main(){
ifstream cin("cuplaj.in");
ofstream cout("cuplaj.out");
int l, r, m;
cin >> l >> r >> m;
Graph G(l, r);
vector < pair <int, int> > edges;
while (m--){
int a, b;
cin >> a >> b;
G.AddEdge(a, l + b);
edges.emplace_back(a, b + l);
}
auto ans = G.maxFlow(edges);
cout << ans.size() << '\n';
for (auto& it: ans)
cout << it.first << ' ' << it.second << '\n';
return 0;
}