Pagini recente » Cod sursa (job #255093) | Monitorul de evaluare | Cod sursa (job #836076) | Cod sursa (job #273606) | Cod sursa (job #2961489)
#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, pair <int, int> > flow[NMAX];
vector <int> edges[NMAX], directedEdges[NMAX];
// flow.first = capacity
// flow.second = flow
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);
flow[x][N1 + y] = make_pair(1, 0);
}
for(int node = 1; node <= N1; node++){
directedEdges[S].push_back(node);
edges[S].push_back(node);
edges[node].push_back(S);
flow[S][node] = make_pair(1, 0);
}
for(int node = N1 + 1; node <= N1 + N2; node++){
directedEdges[node].push_back(D);
edges[D].push_back(node);
edges[node].push_back(D);
flow[node][D] = make_pair(1, 0);
}
}
// 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 && flow[node][it].first - flow[node][it].second == 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] && flow[node][it].first - flow[node][it].second > 0){
wasSeen[it] = true;
dad[it] = node;
Q.push(it);
}
}
}
if(!dad[D])
return false;
node = D;
for(auto it : edges[node]){
if(flow[it][node].first - flow[it][node].second > 0){
int MinFlow = flow[it][node].first - flow[it][node].second;
for(int j = it; j != 0; j = dad[j])
MinFlow = min(MinFlow, flow[dad[j]][j].first - flow[dad[j]][j].second);
flow[it][node].second += MinFlow;
flow[node][it].second -= MinFlow;
for(int j = it; j != 0; j = dad[j]){
flow[dad[j]][j].second += MinFlow;
flow[j][dad[j]].second -= MinFlow;
}
ansFlow += MinFlow;
}
}
return true;
}
int main() {
freopen("cuplaj.in", "r", stdin);
freopen("cuplaj.out", "w", stdout);
read();
bool repeat = true;
while(repeat)
repeat = generateFlow(0);
printf("%d\n", ansFlow);
printMinimumCut(0);
return 0;
}