Cod sursa(job #854084)

Utilizator andrettiAndretti Naiden andretti Data 12 ianuarie 2013 19:39:36
Problema Cuplaj maxim in graf bipartit Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.72 kb
#include<fstream>
using namespace std;

ifstream fin("cuplaj.in");
ofstream fout("cuplaj.out");

const int maxn=20010,inf=999999999;

struct nod{int inf,f;nod *urm;};
nod *l[maxn];

int n1,n2,n,m;
int p,u,nrd=1,flux;
int v[maxn],t[maxn],cc[maxn];

void add(int nod1,int nod2,int cost)
{
	nod *q;
	
	q=new nod;
	q->inf=nod2;
	q->f=cost;
	q->urm=0;
	
	q->urm=l[nod1];
	l[nod1]=q;
}

void cit()
{
	int i,x,y,cost;
	
	fin>>n1>>n2>>m;
	
	for(i=1;i<=m;i++)
	{
		fin>>x>>y;
		add(x+1,y+n1+1,1); 
		add(y+n1+1,x+1,0);
		
		if(v[x+1]==0){ add(1,x+1,1); add(x+1,1,0); v[x+1]=-1;}
		if(v[y+n1+1]==0) { add(y+n1+1,n1+n2+2,1); add(n1+n2+2,y+n1+1,0); v[y+n1+1]=-1;}
	}
	n=n1+n2+2;
}

int drum()
{
    int i,nodc;
	nod *q;
	
    p=u=1; cc[1]=1; v[1]=nrd; t[1]=0;
	
    while(p<=u)
    {
        nodc=cc[p];
		if(nodc==n) return 1;
		
        q=l[nodc];
		while(q)
        {    
			if(q->f>0 && v[q->inf]!=nrd)
            {
                u++;
                cc[u]=q->inf;
                t[q->inf]=nodc;
                v[q->inf]=nrd;
            }
			
		  q=q->urm;
		}
        p++;
    }
	
    return 0;
}

void flow_change(int i)
{
	nod *q;
	
	q=l[t[i]];
	while(q)
	{
		if(q->inf==i) {q->f--; break;} 
		q=q->urm;
	}
	
	q=l[i];
	while(q)
	{
		if(q->inf==t[i]) {q->f++; break;}
		q=q->urm;
	}
}
 
void flux_max()
{
    int i,k;
    
    while(drum())
	{
		for(i=n;t[i]!=0;i=t[i])
		    flow_change(i);
		
		flux++;
		nrd++;
	}
    
}

void afis()
{
	int i,st=n1+2,dr=n1+n2+1;
	
	for(i=st;i<=dr;i++)
		fout<<t[i]-1<<" "<<i-n1-1<<'\n';
}	

int main()
{
	cit();
	flux_max();
	fout<<flux<<'\n';
	afis();

	fin.close();
	fout.close();
	return 0;
}