Pagini recente » Cod sursa (job #2190286) | Cod sursa (job #1983239) | Borderou de evaluare (job #1527663) | Cod sursa (job #969079) | Cod sursa (job #3329907)
#include <bits/stdc++.h>
#include <fstream>
using namespace std;
const int NMAX = 2005;
int capacitate[NMAX + 1][NMAX + 1], flux[NMAX + 1][NMAX + 1];
int vis[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++) {
vis[i] = 0;
p[i] = -1;
}
queue<int> q;
q.push(s);
vis[s] = 1;
while(!q.empty()) {
int nod = q.front();
q.pop();
for(auto vecin : G[nod]) {
if(!vis[vecin] && capacitate[nod][vecin] - flux[nod][vecin] > 0) {
vis[vecin] = 1;
q.push(vecin);
p[vecin] = nod;
}
}
}
if(vis[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;
if (n+m+2 >= NMAX) {
fout << 0 << '\n';
return 0;
}
for(int i = 1; i <= e; i++) {
int x, y, c;
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 + 1; 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;
for (int i = 1; i <= n; i++) {
for (int j = n + 1; j <= n+m; j++) {
if (flux[i][j] == 1)
fout << i << " " << j - n << endl;
}
}
return 0;
}