Pagini recente » Cod sursa (job #1475157) | Cod sursa (job #1204612) | Cod sursa (job #1375457) | Cod sursa (job #1619837) | Cod sursa (job #3329896)
#include <iostream>
#include <fstream>
#include <bits/stdc++.h>
using namespace std;
const int NMAX =1e3;
int capacitate[NMAX+1][NMAX+1], flux[NMAX+1][NMAX+1];
int viz[NMAX+1], p[NMAX+1];
vector<int> G[NMAX+1];
int n, m, e;
int bfs(int s, int d) {
for (int i=0; i<=n+m+1; i++) {
viz[i]=0;
p[i]=-1;
}
queue<int> q;
q.push(s);
viz[s]=1;
while (!q.empty()) {
int nod = q.front();
q.pop();
for (auto vecin : G[nod]) {
if (!viz[vecin] && capacitate[nod][vecin] - flux[nod][vecin] > 0) {
viz[vecin] =1;
q.push(vecin);
p[vecin] = nod;
}
}
}
if (viz[d]==0) {
return 0;
}
vector<int> path;
while (d != -1) {
path.push_back(d);
d = p[d];
}
reverse(path.begin(), path.end());
int flow = 1e9;
for (int i=0; i < path.size() - 1; i++) {
int x=path[i];
int y=path[i+1];
flow = min(flow, capacitate[x][y] - flux[x][y]);
}
for (int i=0; i < path.size() - 1; i++) {
int x=path[i];
int y=path[i+1];
flux[x][y]+=flow;
flux[y][x]-=flow;
}
return flow;
}
int main() {
ifstream fin("cuplaj.in");
ofstream fout("cuplaj.out");
fin>>n>>m>>e;
for (int i=0; i<e; i++) {
int x, y;
fin>>x>>y;
capacitate[x][n+y]=1;
G[x].push_back(n+y);
G[n+y].push_back(x);
}
for (int i=1; i<=n; i++) {
capacitate[0][i] =1;
G[0].push_back(i);
G[i].push_back(0);
}
for (int i= n+1; i<= n+m; i++) {
capacitate[i][n+m+1] = 1;
G[i].push_back(n+m+1);
G[n+m+1].push_back(i);
}
int maxflow =0;
while (true) {
int flow= bfs(0, n+m+1);
if (flow == 0) {
break;
}
maxflow+=flow;
}
fout<<maxflow<<"\n";
for (int i=1; i<= n; i++) {
for (int j=n+1; j<=n+m+1; j++) {
if (flux[i][j] == 1) {
fout<<i<<" "<<j-n<<"\n";
}
}
}
return 0;
}