Pagini recente » Cod sursa (job #2276242) | Cod sursa (job #857312) | Cod sursa (job #2365795) | Cod sursa (job #1557816) | Cod sursa (job #2685986)
#include <iostream>
#include <bits/stdc++.h>
#define MAX 10004
using namespace std;
ifstream in("cuplaj.in");
ofstream out("cuplaj.out");
int N,M,E; // Card multimea 1, card multimea 2, nr muchii
vector<int> Graph[MAX];
bool capacitate[MAX][MAX];
int flow[MAX][MAX];
int start,sink;
int bfs(vector<int> &tata)
{
fill(tata.begin(),tata.end(),-1);
queue<int> que;
que.push(start);
tata[start]=start;
while(!que.empty())
{
int cur = que.front();
que.pop();
for(auto next : Graph[cur])
{
if(tata[next] == -1 && (capacitate[cur][next]-flow[cur][next]>0)) // Daca nu e deja vizitat si mai putem creste fluxul
{
tata[next] = cur;
if(next==sink)
return 1;
que.push(next);
}
}
}
return 0;
}
int main()
{
int x,y;
in>>N>>M>>E;
start = N+M+1;
sink = M+N+2;
for(int i=1; i<=N; i++)
{
capacitate[start][i]=1;
Graph[start].push_back(i);
Graph[i].push_back(start);
}
for(int i=1; i<=M; i++)
{
capacitate[N+i][sink]=1;
Graph[N+i].push_back(sink);
Graph[sink].push_back(N+i);
}
for(int i=1; i<=E; i++)
{
in>>x>>y; //Nod, Nod, capacitatea maxima, capacitatea folosita
Graph[x].push_back(y+N);
Graph[y+N].push_back(x);
capacitate[x][y+N] = 1;
}
vector<int> tata(N+M+4);
int new_flow, current, maxflow=0;
while(new_flow = bfs(tata)) //Cat timp gasim un lant nesaturat
{
maxflow+=new_flow; //Crestem fluxul
current = sink;
while(current!=start) //Updatam capacitatile
{
int previous = tata[current];
flow[previous][current]+=new_flow; // Pe muchiile directe adun fluxul adaugat
flow[current][previous]-=new_flow; // Pe muchiile inverse scad
current = previous;
}
}
out<<maxflow<<'\n';
for(int i=1; i<=N; i++)
for(auto j : Graph[i])
if(flow[i][j]>0)
out<<i<<" "<<j-N<<"\n";
return 0;
}