Pagini recente » Cod sursa (job #938039) | Cod sursa (job #356110) | Cod sursa (job #2871855) | Cod sursa (job #2802474) | Cod sursa (job #522726)
Cod sursa(job #522726)
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define dim 10005
using namespace std;
int *A[dim],n,m,i,x,y,j,L[dim],R[dim],NR,gasit,ok,l1,r1;
short int viz[dim];
void citire()
{
FILE *f=fopen("cuplaj.in","r");
fscanf(f,"%d %d %d",&n,&m,&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 i; // l r
viz[ L[x] ]=1;
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] ])
if( solve(R[ A[x][i] ] ) )
{
L[x]=A[x][i];
R[A[x][i]]=x;
return 1;
}
viz[ L[x] ]=0;
return 0;
}
int main()
{
FILE *g=fopen("cuplaj.out","w");
citire();
for(i=1;i<=n;i++)
{
if(A[i][0] && !L[i])
{ gasit=cauta(i);
if(gasit)
{
NR++;
L[i]=gasit;
R[gasit]=i;
}
else
{
memset(viz,0,sizeof(viz));
for(j=1;j<=A[i][0];j++)
{
y=A[i][j]; l1=L[i];
L[i]=y; r1=R[y];
R[y]=i;
viz[y]=1;
if( solve(r1) )
{ NR++;
break;}
else {L[i]=l1; R[y]=r1;}
viz[y]=0;
}
}
}
}
fprintf(g,"%d\n",NR);
for(i=1;i<=n;i++)
if(L[i] && R[L[i]]==i)
fprintf(g,"%d %d\n",i,L[i]);
fclose(g);
return 0;
}