Pagini recente » Cod sursa (job #2420994) | Cod sursa (job #400903) | Cod sursa (job #518378) | Cod sursa (job #2454609) | Cod sursa (job #2960193)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("cuplaj.in");
ofstream gout("cuplaj.out");
int nodes, edges, s, t, leftt, rightt;
vector<vector<pair<int, pair<int, int>>>> graphh;
vector<pair<int, int>> parrent;
void addedge(int x, int y){
graphh[x].push_back({y, {1,graphh[y].size()}});
graphh[y].push_back({x, {0,graphh[x].size()-1}});
}
void read(){
fin>>leftt>>rightt>>edges;
nodes=leftt+rightt;
graphh.resize(nodes+3);
parrent.resize(nodes+3);
for(int i=0;i<edges;i++){
int x,y;
fin>>x>>y;
addedge(x,y+leftt);
}
for(int i=1;i<=leftt;i++){
addedge(0,i);
}
for(int i=leftt+1;i<=leftt+rightt;i++) {
addedge(i,nodes+1);
}
s=0;
t=nodes+1;
}
bool bfs(){
vector <bool> viz(nodes+3);
queue<int> q;
q.push(s);
viz[s]=true;
parrent[s]={-1,-1};
while(!q.empty()){
int current_node = q.front();
q.pop();
int i=0;
for(auto adj: graphh[current_node]){
int c=adj.second.first;
int adj_node=adj.first;
if(!viz[adj_node] && c){
parrent[adj_node]={current_node, i};
if(adj_node==t){
return true;
}
viz[adj_node]=true;
q.push(adj_node);
}
i++;
}
}
return false;
}
int edmondsKarp(){
long flux_max=0;
while(bfs()){
int x=t, path_min=1;
while(parrent[x].first!=-1){
int u=parrent[x].first;
int v=parrent[x].second;
path_min=min(path_min, graphh[u][v].second.first);
x=parrent[x].first;
}
x=t;
while(parrent[x].first!=-1){
int u=parrent[x].first;
int v=parrent[x].second;
int w=graphh[u][v].second.second;
graphh[u][v].second.first-=path_min;
graphh[x][w].second.first+=path_min;
x=parrent[x].first;
}
flux_max += path_min;
}
return flux_max;
}
int main(){
read();
gout << edmondsKarp() << '\n';
for(int u = 1; u <= leftt; u++)
for(auto node: graphh[u]){
int v, c;
v = node.first;
c = node.second.first;
if(v && c == 0 && v != t)
gout << u << " " << v-leftt << '\n';
}
return 0;
}