Pagini recente » Cod sursa (job #2032147) | Cod sursa (job #2673587) | Cod sursa (job #1447486) | Cod sursa (job #3336709) | Cod sursa (job #3332265)
#include <fstream>
#include <cstring>
#include <queue>
#include <vector>
#define nmax 20005
#define mmax (int)(1e5+1)
#define inf 1e9
using namespace std;
ifstream cin("cuplaj.in");
ofstream cout("cuplaj.out");
int n1,n2,m,s,d,x,y,dist[nmax],maxflow,nr,start[nmax];
struct edge{
int flow,c;
};
struct muchie{
int x,y,id;
}e[mmax];
vector<edge>mch;
struct elem{
int x,id,idr;
};
vector<elem>v[nmax];
queue<int>q;
bool bfs(int s,int d){
for(int i=0;i<nmax;i++)
dist[i]=inf;
dist[s]=0;
q.push(s);
while(!q.empty()){
int nod=q.front();
q.pop();
for(auto i:v[nod])
if(dist[i.x]>dist[nod]+1&&mch[i.id].flow<mch[i.id].c){
dist[i.x]=dist[nod]+1;
q.push(i.x);
}
}
return dist[d]!=inf;
}
int dinic(int nod,int d,int val){
if(val==0)
return 0;
if(nod==d)
return val;
int total=0;
for(int j=start[nod];j<v[nod].size();j++){
elem i=v[nod][j];
if(dist[i.x]==dist[nod]+1&&mch[i.id].flow<mch[i.id].c){
int add=dinic(i.x,d,min(val-total,mch[i.id].c-mch[i.id].flow));
mch[i.id].flow+=add;
mch[i.idr].flow-=add;
total+=add;
}
}
return total;
}
void add_edge(int x,int y){
mch.push_back({0,1});
v[x].push_back({y,nr,nr+1});
nr++;
mch.push_back({0,0});
v[y].push_back({x,nr,nr-1});
nr++;
}
signed main()
{
cin>>n1>>n2>>m;
d=nmax-1;
for(int i=1;i<=n1;i++)
add_edge(0,i);
for(int i=1;i<=n2;i++)
add_edge(i+n1,d);
for(int i=1;i<=m;i++){
cin>>x>>y;
e[i]={x,y,nr};
add_edge(x,y+n1);
}
while(bfs(0,d)){
memset(start,0,sizeof(start));
int val=dinic(0,d,inf);
while(val!=0){
maxflow+=val;
val=dinic(0,d,inf);
}
}
cout<<maxflow<<'\n';
for(int i=1;i<=m;i++)
if(mch[e[i].id].flow==1)
cout<<e[i].x<<" "<<e[i].y<<'\n';
return 0;
}