Cod sursa(job #1452313)

Utilizator mikeshadowIon Complot mikeshadow Data 20 iunie 2015 15:48:46
Problema Flux maxim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 2.09 kb
#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
#include <queue>

using namespace std;


typedef long long ll;
//////////////

//max flow ver 1.0

struct edge
{
	int from;
	int to;
	int cap;
	int flow;

	int revid;

	int resid()
	{
		return cap - flow;
	}
};

#define pb push_back

typedef vector<int> vi;
vector<edge> *graph;
int sz = 0;

int source, sink;

int *touched;

void init(int n, int s, int t)
{
	sz = n;
	touched = new int[sz+1];
	graph = new vector<edge>[sz+1];
	for (int i=0; i<=sz; i++) graph[i].clear();
	source = s;
	sink = t;
}

void addedge(int from, int to, int cap)
{
	edge e;
	e.from = from;
	e.to = to;
	e.cap = cap;
	e.flow = 0;
	e.revid = graph[to].size();
	graph[from].pb(e);
	e.revid = graph[from].size()-1;
	swap (e.from,e.to);
	e.cap = 0;
	graph[to].pb(e);
}

bool found = 0;
const int inf = 1000000001;

void bfspath()
{
	for (int i =0; i<=sz; i++ )
		touched[i] = 0;
	found  = 0;


	queue<int> q;
	q.push(source);
	touched[source]=1;
	while (!q.empty() && !touched[sink])
	{
		int r;
		r = q.front();
		q.pop();

		for (auto i:graph[r])
		{
			if (touched[i.to]) continue;
			if (!i.resid()) continue;
			touched[i.to] = i.revid+1;
			q.push(i.to);
		}
	}

	if (!touched[sink]) return;
	else found=1;

	int m = inf;
	int t = sink;
	while (t!=source)
	{
		int id = touched[t]-1;
		int l = graph[t][id].to;
		id = graph[t][id].revid;
		m = min(m,graph[l][id].resid());
		t=l;
	}

	t = sink;
	while (t!=source)
	{
		int id = touched[t]-1;
		int l = graph[t][id].to;
		id = graph[t][id].revid;

		{
			graph[l][id].flow+=m;
			id = graph[l][id].revid;
			graph[t][id].flow-=m;
		}

		t=l;
	}
}


ll maxflow()
{
	while (true)
	{
		bfspath();
		if (!found) break;
	}
	ll flow = 0;
	for (auto i:graph[source])
		flow+=i.flow;
	return flow;
}

///////////
#ifdef home
ifstream fin("input.txt");
ofstream fout("output.txt");
#else
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");
#endif

int n,m;
int main()
{
	fin.tie(0);
	fin>>n>>m;

	init(n,1,n);
	for (int i=0; i<m; i++)
	{
		int x,y,z;
		fin>>x>>y>>z;
		addedge(x,y,z);
	}

	ll rez = maxflow();
	fout<<rez;

	return 0;
}