Cod sursa(job #588896)

Utilizator edward_alexStanciu Alexandru Marian edward_alex Data 9 mai 2011 22:08:01
Problema Cuplaj maxim in graf bipartit Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.92 kb
#include<iostream>
#include<fstream>
#include<vector>
#include<queue>

using namespace std;

#define INF 1000

vector<int> a[100000];
int tuplu[100000];
int dist[100000];

inline int maxim(int a,int b)
{
     return ((a > b) ? a : b);
}

inline int minim(int a,int b)
{
     return ((a < b) ? a : b);
}

bool bfs(int n,int m)
{
     queue<int> q;
     for(int i = 1 ; i <= n ; i++)
     {
	  if(tuplu[i] == -1)
	  {
	       dist[i] = 0;
	       q.push(i);
	  }
	  else
	       dist[i] = INF;
     }
     dist[-1] = INF;
     while(q.empty() != true)
     {
	  int v = q.front();
	  q.pop();
	  if(v != -1)
	  {
	       vector<int>::iterator it;
	       for(it = a[v].begin() ; it != a[v].end() ; it++)
	       {
		    if(dist[tuplu[*it]] == INF)
		    {
			 dist[tuplu[*it]] = dist[v] + 1;
			 q.push(tuplu[*it]);
		    }
	       }
	  }
     }
     return (dist[-1] != INF);
}

bool dfs(int n,int m,int v)
{
     if(v != -1)
     {
	  vector<int>::iterator it;
	  for(it = a[v].begin() ; it != a[v].end() ; it++)
	  {
	       if(dist[tuplu[*it]] == dist[v] + 1)
	       {
		    if(dfs(n,m,tuplu[*it]) == true)
		    {
			 tuplu[*it] = v;
			 tuplu[v] = *it;
			 //cout<<v<<" "<<*it<<endl;
			 return true;
		    }
	       }
	  }
	  dist[v] = INF;
	  return false;
     }
     return true;
}

void HopcroftKarp(int n,int m)
{
     for(int i = 1 ; i <= maxim(n,m) ; i++)
	  tuplu[i] = -1;
     int matching = 0;
     while(bfs(n,m) == true)
     {
	  for(int i = 1; i <= n ; i++)
	  {
	       if(tuplu[i] == -1)
		    if(dfs(n,m,i) == true)
			 matching += 1;
	  }
     }
     fstream out("cuplaj.out",fstream::out);
     out<<matching<<endl;
     for(int i = 1 ; i <= minim(n,m) ; i++)
     {
	  out<<i<<" "<<tuplu[i]<<endl;
     }
}

int main()
{
     int n,m,e;
     fstream in("cuplaj.in",fstream::in);
     in>>n>>m>>e;
     for(int i = 0 ; i < e ; i++)
     {
	  int k1,k2;
	  in>>k1>>k2;
	  a[k1].push_back(k2);
     }
     HopcroftKarp(n,m);
     
     return 0;
}