Pagini recente » Monitorul de evaluare | Profil mihaistamatescu | Cod sursa (job #966087) | Cod sursa (job #2485764) | Cod sursa (job #3261330)
#include <bits/stdc++.h>
using namespace std;
const int NMAX = 1000;
vector<int> G[NMAX + 1];
int capacitate[NMAX + 1][NMAX + 1], flux[NMAX + 1][NMAX + 1];
int n, m, e;
int bfs(int s, int d) {
queue<int> q;
int vis[NMAX + 1], p[NMAX + 1];
for(int i = 0; i <= n + m + 1; i++) {
vis[i] = 0;
p[i] = -1;
}
vis[s] = 1;
q.push(s);
while(!q.empty()) {
int node = q.front();
q.pop();
for(auto vecin : G[node]) {
if(!vis[vecin]) {
if(capacitate[node][vecin] - flux[node][vecin] > 0) {
q.push(vecin);
vis[vecin] = 1;
p[vecin] = node;
}
}
}
}
if(!vis[d]) {
return -1;
}
vector<int> path;
while(d != -1) {
path.push_back(d);
d = p[d];
}
reverse(path.begin(), path.end()); //nu e obligatoriu sa facem asta
int mn = 1e9;
for(int i = 0; i < (int)path.size() - 1; i++) {
int x = path[i];
int y = path[i + 1];
mn = min(mn, capacitate[x][y] - flux[x][y]);
}
for(int i = 0; i < (int)path.size() - 1; i++) {
int x = path[i];
int y = path[i + 1];
flux[x][y] += mn;
flux[y][x] -= mn;
}
return mn;
}
int main() {
ifstream f("cuplaj.in");
ofstream g("cuplaj.out");
f >> n >> m >> e;
for(int i = 1; i <= e; i++) {
int x, y;
f >> x >> y;
y = n + y;
capacitate[x][y] = 1;
G[x].push_back(y);
G[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 == -1) {
break;
}
maxFlow += flow;
}
g << maxFlow << '\n';
for(int i = 1; i <= n; i++) {
for(auto j : G[i]) {
if(flux[i][j] == 1) {
g << i << ' ' << j - n << '\n';
}
}
}
return 0;
}