Pagini recente » Cod sursa (job #1059764) | Cod sursa (job #1415265) | Cod sursa (job #2222442) | Cod sursa (job #1175404) | Cod sursa (job #2961479)
#include <bits/stdc++.h>
using namespace std;
const int NMAX = 20100;
int N1, N2, M, ansFlow, S, D;
bool wasSeen[NMAX];
int dad[NMAX];
unordered_map <int, int> flow[NMAX], capacity[NMAX];
vector <int> edges[NMAX], directedEdges[NMAX];
void read(){
scanf("%d%d%d", &N1, &N2, &M);
int x, y;
S = 0;
D = N1 + N2 + 1;
for(int i = 1; i <= M; i++){
scanf("%d%d", &x, &y);
directedEdges[x].push_back(N1 + y);
edges[x].push_back(N1 + y);
edges[N1 + y].push_back(x);
capacity[x][N1 + y] = 1;
}
for(int node = 1; node <= N1; node++){
directedEdges[S].push_back(node);
edges[S].push_back(node);
edges[node].push_back(S);
capacity[S][node] = 1;
}
for(int node = N1 + 1; node <= N1 + N2; node++){
directedEdges[node].push_back(D);
edges[D].push_back(node);
edges[node].push_back(D);
capacity[node][D] = 1;
}
}
// rezolvare cerinta a
// aplic algoritmul de flux, pornesc un BFS din nodul 1 si incerc sa ajung in nodul N pe muchiile care inca nu
// si-au atins capacitatea maxima, iar pentru fiecare nod retin nodul de unde am venit
// pentru toti vecinii lui N, calculez fluxul cu care pot sa ajung intr-un vecin de a lui, uitandu-ma la tatii acestuia
// insumez toate fluxurile gasite si obtin rezultatul
void printMinimumCut(int node){
for(int i = 0; i <= D; i++)
wasSeen[i] = false;
vector <pair <int, int> > cutEdges;
queue <int> Q;
Q.push(node);
wasSeen[node] = true;
while(!Q.empty()){
node = Q.front();
Q.pop();
for(auto it : directedEdges[node]){
if(node != S && it != D && capacity[node][it] - flow[node][it] == 0){
cutEdges.push_back(make_pair(node, it - N1));
continue;
}
if(!wasSeen[it]) {
wasSeen[it] = true;
Q.push(it);
}
}
}
for(auto it : cutEdges)
printf("%d %d\n", it.first, it.second);
}
bool generateFlow(int node){
for(int i = 0; i <= D; i++){
wasSeen[i] = false;
dad[i] = 0;
}
queue <int> Q;
Q.push(node);
wasSeen[node] = true;
while(!Q.empty()){
node = Q.front();
Q.pop();
for(auto it : edges[node]){
if(!wasSeen[it] && capacity[node][it] - flow[node][it] > 0){
wasSeen[it] = true;
dad[it] = node;
Q.push(it);
}
}
}
if(!dad[D])
return false;
node = D;
for(auto it : edges[node]){
if(capacity[it][node] - flow[it][node] > 0){
int MinFlow = capacity[it][node] - flow[it][node];
for(int j = it; j != 0; j = dad[j])
MinFlow = min(MinFlow, capacity[dad[j]][j] - flow[dad[j]][j]);
flow[it][node] += MinFlow;
flow[node][it] -= MinFlow;
for(int j = it; j != 0; j = dad[j]){
flow[dad[j]][j] += MinFlow;
flow[j][dad[j]] -= MinFlow;
}
ansFlow += MinFlow;
}
}
return true;
}
int main() {
freopen("maxflow.in", "r", stdin);
freopen("maxflow.out", "w", stdout);
read();
bool repeat = true;
while(repeat)
repeat = generateFlow(0);
printf("%d\n", ansFlow);
printMinimumCut(0);
return 0;
}