Pagini recente » Cod sursa (job #3235561) | Cod sursa (job #2200100) | Cod sursa (job #101060) | Cod sursa (job #498391) | Cod sursa (job #2957416)
#include <iostream>
#include <vector>
#include <fstream>
#include <queue>
#define max_capacity INT_MAX
using namespace std;
ifstream fin("cuplaj.in");
ofstream fout("cuplaj.out");
int n, m, e, max_flow;
int capacity[20002][20002];
vector<int>parent, visited;
vector<int>adjacency_list[20002];
queue<int>q;
int bfs(){
visited.assign(n+m+2, 0);
parent.assign(n+m+2, 0);
while(!q.empty()){
q.pop();
}
q.push(0);
visited[0]=1;
parent[0]=0;
while(!q.empty()){
int node=q.front();
q.pop();
for(auto neighbour:adjacency_list[node]){
if(visited[neighbour]==0 && capacity[node][neighbour]>0) {
q.push(neighbour);
parent[neighbour]=node;
visited[neighbour]=1;
if(neighbour == n+m+1) return 1;
}
}
}
return visited[n+m+1];
}
int main() {
fin>>n>>m>>e;
int x, y;
for(int i=0; i<e; i++){
fin>>x>>y;
y += n;
adjacency_list[x].push_back(y);
adjacency_list[y].push_back(x);
adjacency_list[0].push_back(x);
adjacency_list[x].push_back(0);
adjacency_list[y].push_back(n+m+1);
adjacency_list[n+m+1].push_back(y);
capacity[x][y]=1;
capacity[0][x]=1;
capacity[y][n+m+1]=1;
}
while(bfs()) {
for (auto node: adjacency_list[n+m+1]) {
if (!visited[node])
continue;
parent[n+m+1] = node;
int flow = max_capacity;
for (node = n+m+1; node != 0; node = parent[node]) {
flow = min(flow, capacity[parent[node]][node]);
}
if (flow == 0) continue;
for (node = n+m+1; node != 0; node = parent[node]) {
capacity[parent[node]][node] -= flow;
capacity[node][parent[node]] += flow;
}
max_flow += flow;
}
}
fout<<max_flow<<'\n';
for(int i=1; i<=n; i++){
for(int j=n+1; j<=m+n+1; j++){
if(capacity[i][j] == 0 && capacity[j][i] == 1){
fout<<i<<" "<<j-n<<'\n';
}
}
}
fin.close();
fout.close();
return 0;
}