Cod sursa(job #301778)

Utilizator SleepyOverlordPatcas Csaba SleepyOverlord Data 8 aprilie 2009 13:59:18
Problema Flux maxim Scor 60
Compilator cpp Status done
Runda Arhiva educationala Marime 1.52 kb
//Code by Patcas Csaba
//Time complexity: O(F*n^2)
//Space complexity: O(n^2)
//Method: Ford-Fulkerson dupa capul meu pe matrice
//Working time: 30 minutes

#include <stdio.h>
#include <vector>

using namespace std;

#define in_file "maxflow.in"
#define out_file "maxflow.out"

#define VI vector <int>

#define FORN(i,n) for (int i=0;i<n;++i)
#define FOR(i,a,b) for (int i=a;i<=b;++i)
#define ALL(x) x.begin(), x.end()

#define inf 111111

int n,m,solution;
vector <VI> cap,f;
vector <bool> was;

int df(int node, int flow)
{
	was[node]=true;
	if (node==n) return flow;
	else
	{
		FOR(q,1,n)
			if (!was[q] && cap[node][q]!=-1 && cap[node][q]>f[node][q])
			{
				int aux=df(q,min(flow,cap[node][q]-f[node][q]));
				if (aux)
				{
					f[node][q]+=aux;
					return aux;
				}
			}
		FOR(q,1,n)
			if (!was[q] && cap[q][node]!=-1 && f[q][node])
			{
				int aux=df(q,min(flow,f[q][node]));
				if (aux)
				{
					f[q][node]-=aux;
					return aux;
				}
			}
		return 0;
	}
}

void FordFulkerson()
{
	f.resize(n+1,VI (n+1));
	was.resize(n+1);
	solution=0;
	while (1) 
	{
		fill(ALL(was),false);
		int aux=df(1,inf);
		if (aux) solution+=aux;
		else break;
	}
}

int main()
{
	FILE* fin=fopen(in_file,"r");
	fscanf(fin,"%d%d",&n,&m);
	cap.resize(n+1,VI (n+1,-1));
	FORN(q,m)
	{
		int x,y,z;
		fscanf(fin,"%d%d%d",&x,&y,&z);
		cap[x][y]=z;
	}
	fclose(fin);

	FordFulkerson();

	FILE* fout=fopen(out_file,"w");
	fprintf(fout,"%d",solution);
	fclose(fout);

	return 0;
}