Cod sursa(job #6242)

Utilizator rusRus Sergiu rus Data 18 ianuarie 2007 16:26:46
Problema Cc Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.07 kb
#include<stdio.h>
#define max1 54
#include<iomanip.h>
#include<math.h>

typedef struct nod{
	int info;
	nod*urm;
	}*PNOD,NOD;
PNOD l[max];

int c[max1][max1],cost[max1][max1],f[max1][max1];
int d[max1],t[max1];
int n;
int flow=0;

void citire();
void add(int ,int );
int bellman();
void solve();
void drum();
int minimizeaza();
void afisare();

int main()
{
	freopen("cc.in","r",stdin);
	freopen("cc.out","w",stdout);

	citire();
	solve();
	afisare();

	return 0;
}
void citire()
{
	int i,j,x;
	scanf("%d",&n);

	for(i=1;i<=n;i++)
	{
		for(j=1;j<=n;j++)
		{
			scanf("%d",&x);
			add(i , j + n);
			add (j + n, i);
			cost[i][j+n]=cost[j+n][i]=x;
			c[i][j+n]=c[j+n][i]=1;

			//printf("%d  ",x);
		}

		//printf("\n");
	}

	for(i=1;i<=n;i++)
	{
		add ( 0 , i);
		add ( i , 0);
		c[0][i]=1;
		cost[0][i]=c[i][0]=0;

	}

	for(i=n+1;i<=n+n;i++)
	{
		add (i , n+n+1);
		add (n+n+1 , i);
		c[i][n+n+1]=c[n+n+1][i]=1;
	}

	//for(PNOD p=l[n+n+1];p;p=p->urm)
	//printf("%d ",p->info);

}
void add(int i,int j)
{
	PNOD p=new NOD;
	p->info=j;
	p->urm=l[i];
	l[i]=p;
}
void solve()
{
	while(bellman())
	drum();
}
int bellman()
{
	int i;
	for(i=0;i<=n+n+1;i++)
	{
		d[i]=2000;
		t[i]=0;
	}
	d[0]=0;
	for(i=1;i<=n+n+1;i++)
	minimizeaza();
	if(d[n+n+1]==2000)
	return 0;
	return 1;
}
void drum()
{
	int i,j;
	i=n+n+1;
	while(i)
	{
		j=abs(t[i]);
		if(t[i]>=0) f[j][i]++;
		else
			    f[i][j]--;
		i=j;
	}
	flow++;
}
int minimizeaza()
{
	int i,j,ok;
	ok=0;
	for(i=0;i<=n+n+1;i++)
		for(PNOD p=l[i];p;p=p->urm)
		{
			j=p->info;

			if(c[i][j]>f[i][j])
				if(d[j]>d[i]+cost[i][j])
				{
					d[j]=d[i]+cost[i][j];
					t[j]=i;
					ok=1;
					if(j==n+n+1) return 1;
				}
			if(f[j][i])
			   if(d[j]>d[i]-cost[i][j])
			   {
				d[j]=d[i]-cost[i][j];
				t[j]=-i;
				ok=1;
				if(j==n+n+1) return 1;
			   }
		}
	return ok;
}

void afisare()
{
	int i,j,sol=0;


	for(i=1;i<=n+n+1;i++)
	{
		for(j=1;j<=n+n+1;j++)

		if(f[i][j])
		sol+=cost[i][j];
	}
	printf("%d",sol);
}