Pagini recente » Cod sursa (job #1615568) | Cod sursa (job #1364690) | Cod sursa (job #2186539) | Cod sursa (job #2904960) | Cod sursa (job #2958482)
/*
* Edmonds-Karp's algorithm
* Complexity: O(V*E^2)
* https://www.infoarena.ro/problema/cuplaj
*/
#include <bits/stdc++.h>
using namespace std;
ifstream in("cuplaj.in");
ofstream out("cuplaj.out");
int leftSize, rightSize, edges, s, t;
vector<int> parrent;
vector<vector<int>> adjListRes;
vector<vector<int>> capacity;
void addEdge(int u, int v){
adjListRes[u].push_back(v);
adjListRes[v].push_back(u);
capacity[u][v] = 1;
}
void init() {
s = 0;
t = leftSize+rightSize+1;
parrent.resize(t+1);
adjListRes.resize(t+1);
capacity.resize(t+1, vector<int>(t+1));
for(int i = 1; i <= leftSize; i++)
addEdge(s, i);
for(int i = 1; i <= rightSize; i++)
addEdge(leftSize+i, t);
}
void read(){
in >> leftSize >> rightSize >> edges;
init();
for(int i = 1; i <= edges; i++){
int u, v;
in >> u >> v;
addEdge(u, leftSize + v);
}
}
bool bf(){
vector<bool> visited(t);
queue<int> q;
q.push(s);
visited[s] = true;
parrent[s] = -1;
while(!q.empty()){
int u = q.front();
q.pop();
for(auto v: adjListRes[u]){
if(!visited[v] and capacity[u][v]){
parrent[v] = u;
if(v == t)
return true;
visited[v] = true;
q.push(v);
}
}
}
return false;
}
int maxFlow(){
long max_flow = 0;
set<int> temp;
while(bf()){
int u, v, path_flow = INT_MAX;
for(v = t; v != s; v = parrent[v]){
u = parrent[v];
if(capacity[u][v] < path_flow)
path_flow = capacity[u][v];
}
for(v = t; v != s; v = parrent[v]){
u = parrent[v];
capacity[u][v] -= path_flow;
capacity[v][u] += path_flow;
}
max_flow += path_flow;
}
return max_flow;
}
vector<pair<int, int>> solution(){
vector<bool> visited(t);
stack<int> stack;
stack.push(s);
vector<pair<int, int>> solution;
while(!stack.empty()){
int u = stack.top();
stack.pop();
visited[u] = true;
if(u > leftSize && u != t)
solution.emplace_back(parrent[u], u-leftSize);
for(auto v: adjListRes[u]){
if(!visited[v] && capacity[v][u]){
parrent[v] = u;
stack.push(v);
}
}
}
return solution;
}
int main() {
read();
out << maxFlow() << '\n';
return 0;
}