Cod sursa(job #522398)

Utilizator mvbinfoDragos Dinca mvbinfo Data 15 ianuarie 2011 00:20:15
Problema Cuplaj maxim in graf bipartit Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.66 kb
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define dim 10005
using namespace std;

int *A[dim],n,m,i,x,y,viz[dim],j,N,l[dim],r[dim],L[dim],R[dim],NR,gasit,ok;

void citire()
{
	FILE *f=fopen("cuplaj.in","r");
	
fscanf(f,"%d %d %d",&n,&N,&m);

for(i=0;i<=n;i++)
{
	A[i]=(int *) realloc (A[i] , sizeof(int));
	A[i][0]=0;
}


for(i=1;i<=m;i++)
{
	fscanf(f,"%d %d",&x,&y);
		
	A[x][0]++;
	A[x]=(int *)realloc (A[x],(A[x][0]+1) * sizeof(int));
	A[x][A[x][0]]=y;	
}

fclose(f);
}


int cauta(int x)
{
	int i;
	
	for(i=1;i<=A[x][0];i++)
		if(! R[ A[x][i] ])
			return A[x][i];
	return 0;	
}

int solve(int x, int l[], int r[] )
{
	int i, y; // l r
	
	gasit=cauta(x);
	
	if( gasit )
	{
		l[x]=gasit;
		r[gasit]=x;
		return 1;
	}
	else
	for(i=1;i<=A[x][0];i++)
		if(!viz[ A[x][i] ])
		{
		y=A[x][i];
		l[x]=y;
		r[y]=x;
		viz[y]=1;
		
		if(!ok)
			{if( solve(y,l,r ) )
				{ok=1; break;}
			}
		else return 1;
		
		viz[y]=0;
		} 
	
	if(!ok)
		return 0;	
	else return 1;
}



int main()
{
	FILE *g=fopen("cuplaj.out","w");
	
	citire();
	

for(i=1;i<=n;i++)
{
	if(A[i][0])
	{	gasit=cauta(i);
	
	if(gasit)
	{
		NR++;
	L[i]=gasit;
	R[gasit]=i;	
	}
	else
	{
		memcpy(l,L,sizeof(l));
		memcpy(r,R,sizeof(r));
		memset(viz,0,sizeof(viz));
		ok=0;
		
		for(j=1;j<=A[i][0];j++)
		{
		y=A[i][j]; viz[y]=1;
		
					
		if( solve(y,l,r) )
			{
				NR++;
				memcpy(L,l,sizeof(L));
				memcpy(R,r,sizeof(R));
				L[i]=y; break;}
		
		viz[y]=0;
		
		}	
	}
	}

}
	
	
	
fprintf(g,"%d\n",NR);
for(i=1;i<=n;i++)
	if(L[i])
	fprintf(g,"%d %d\n",i,L[i]);

fclose(g);
return 0;
}