Cod sursa(job #301820)

Utilizator SleepyOverlordPatcas Csaba SleepyOverlord Data 8 aprilie 2009 14:29:01
Problema Flux maxim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.95 kb
//Code by Patcas Csaba
//Time complexity: O(F*m)
//Space complexity: O(m)
//Method: Ford-Fulkerson dupa capul meu numai pe liste de vecini
//Working time: 10 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 PB push_back
#define S size()

#define inf 111111

struct Tedge
{
	int node,cap,f,inv;
};

int n,m,solution;
vector <vector <Tedge> > g, g2;
vector <bool> was;

int df(int node, int flow)
{
	was[node]=true;
	if (node==n) return flow;
	else
	{
		FORN(i,g[node].S)
		{
			Tedge q=g[node][i];
			if (!was[q.node] && q.cap>q.f)
			{
				int aux=df(q.node,min(flow,q.cap-q.f));
				if (aux)
				{
					g[node][i].f+=aux;
					g2[q.node][q.inv].f+=aux;
					return aux;
				}
			}
		}
		FORN(i,g2[node].S)
		{
			Tedge q=g2[node][i];
			if (!was[q.node] && q.f)
			{
				int aux=df(q.node,min(flow,q.f));
				if (aux)
				{
					g2[node][i].f-=aux;
					g[q.node][q.inv].f-=aux;
					return aux;
				}
			}
		}
		return 0;
	}
}

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

void AddEdge(int node1, int node2, int c)
{
	Tedge aux;
	aux.node=node2;
	aux.cap=c;
	aux.f=0;
	g[node1].PB(aux);

	aux.node=node1;
	aux.cap=c;
	aux.f=0;
	aux.inv=g[node1].S-1;
	g2[node2].PB(aux);
	g[node1][g[node1].S-1].inv=g2[node2].S-1;
}

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

	FordFulkerson();

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

	return 0;
}