Cod sursa(job #301929)

Utilizator SleepyOverlordPatcas Csaba SleepyOverlord Data 8 aprilie 2009 15:35:51
Problema Flux maxim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.98 kb
//Code by Patcas Csaba
//Time complexity: O(n*m^2)
//Space complexity: O(n^2)
//Method: Edmonds-Karp dupa capul meu pe matrice
//Working time: 15:33-

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

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 PB push_back
#define S size()

#define inf 111111


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

void bf()
{
	queue <int> l;
	l.push(1);
	while (!father[n] && !l.empty())
	{
		int node=l.front();
		FOR(aux,1,n)
		{
			if (!father[aux] && cap[node][aux]!=-1 && cap[node][aux]>f[node][aux])
			{
				father[aux]=node;
				l.push(aux);
			}
		}
		FOR(aux,1,n)
		{
			if (!father[aux] && cap[aux][node]!=-1 && f[aux][node])
			{
				father[aux]=-node;
				l.push(aux);
			}
		}
		l.pop();
	}
}

int IncreaseFlow()
{
	int node=n, flow=inf;
	while (node!=1)
	{
		if (father[node]>0)	flow=min(flow,cap[father[node]][node]-f[father[node]][node]);
		else flow=min(flow,f[node][-father[node]]);
		node=abs(father[node]);
	}
	node=n;
	while (node!=1)
	{
		if (father[node]>0) f[father[node]][node]+=flow;
		else f[node][-father[node]]-=flow;
		node=abs(father[node]);
	}
	return flow;
}

void EdmondsKarp()
{
	father.resize(n+1);
	solution=0;
	while (1) 
	{
		fill(ALL(father),0);
		bf();
		if (father[n]) 
		{
			int aux=IncreaseFlow();
			solution+=aux;
		}
		else break;
	}
}

void AddEdge(int node1, int node2, int c)
{
	cap[node1][node2]=c;
}

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

	EdmondsKarp();

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

	return 0;
}