Pagini recente » Cod sursa (job #381884) | Infoarena Monthly 2012 - Sponsori si premii | Cod sursa (job #1114850) | Cod sursa (job #2553592) | Cod sursa (job #1436745)
#include <fstream>
#include <list>
#include <string.h>
using namespace std;
ifstream f1("cuplaj.in");
ofstream f2("cuplaj.out");
#define MX 20*1001
#define NIL 0
#define INF 0x0fffffff
#define FORU(it,G) for(list<int>::iterator it=G.begin(); it != G.end(); it++)
int n,m, e, nr_cuplaje;
list<int> Graf[MX];
int Pair[MX], dist[MX];
bool BFS()
{
int u;
list<int> Q;
for (u=1; u<=n; u++)
if ( Pair[u] == NIL )
{
Q.push_back(u);
dist[u]= 0;
}
else
dist[u]= INF;
dist[NIL]= INF;
while ( !Q.empty() )
{
u= *Q.begin();
Q.pop_front();
if ( dist[u] < dist[NIL] )
FORU(v,Graf[u])
if ( dist[ Pair[*v] ] == INF )
{
dist[ Pair[*v] ]= dist[u]+1;
Q.push_back( Pair[*v] );
}
}
return dist[NIL] != INF;
}
bool DFS(int nod)
{
if ( nod != NIL)
{
FORU(v,Graf[nod])
if ( dist[ Pair[*v] ] == dist[nod]+1 )
if ( DFS( Pair[*v] ) )
{
Pair[*v]= nod;
Pair[nod]= *v;
return true;
}
return false;
}
return true;
}
void Hopfkropf_Karp()
{
int u;
while ( BFS() )
for (u=1; u<=n; u++)
if ( Pair[u] == NIL && DFS(u) ) // u can be paired
nr_cuplaje++;
}
int main()
{
int i, x, y;
f1>>n>>m>>e;
for (i=1; i<=e; i++)
{
f1>>x>>y;
Graf[x].push_back( y + n ); // inlocuiesc y cu y+n
Graf[ y + n ].push_back(x);
}
Hopfkropf_Karp();
f2<<nr_cuplaje<<"\n";
for (i=1; i<=n; i++)
if ( Pair[i] != NIL )
f2<<i<<" "<<Pair[i] - n<<"\n"; // pun y din graful initial
f2.close();
return 0;
}