Cod sursa(job #1688207)

Utilizator Cristian1997Vintur Cristian Cristian1997 Data 13 aprilie 2016 12:25:31
Problema Flux maxim Scor 30
Compilator cpp Status done
Runda Arhiva educationala Marime 1.54 kb
using namespace std;
#include <fstream>
#include <vector>
#include <algorithm>
#include <string>
#include <queue>
using pii = pair<int, int>;
#define Nmax 1001

int n, max_flow;
int father[Nmax];
int f[Nmax][Nmax], c[Nmax][Nmax];
queue< int > Q;
vector< int > G[Nmax];
vector< bool > vis;

bool BFS(int);
void read();
void write();

int main()
{
	int cf, vf;

	read();

	while (BFS(1))
	{
		for (auto &to : G[n])
			if(vis[to] && f[to][n] < c[to][n])
			{
				for (cf = c[to][n] - f[to][n], vf = to; father[vf] != 0; vf = father[vf])
					if (c[father[vf]][vf] - f[father[vf]][vf] < cf)
						cf = c[father[vf]][vf] - f[father[vf]][vf];

				if(cf > 0)
					for (vf = to; father[vf] != 0; vf = father[vf])
					{
						f[father[vf]][vf] += cf;
						f[vf][father[vf]] -= cf;
					}

				max_flow += cf;
			}
	}

	write();

    return 0;
}

bool BFS(int vf)
{
	vis.assign(n + 1, false);

	vis[vf] = true;
	father[vf] = 0;
	for (Q.push(vf); !Q.empty(); Q.pop())
	{
		vf = Q.front();
		if (vf == n) continue;

		for(auto &to : G[vf])
			if (!vis[to] && f[vf][to] < c[vf][to])
			{
				father[to] = vf;

				vis[to] = true;			
				Q.push(to);
			}
	}

	return vis[n];
}

void read()
{
	int m, a, b, C;
	ifstream fin("maxflow.in");

	fin >> n;
	vis.resize(n + 1);

	for (fin >> m; m; --m)
	{
		fin >> a >> b >> C;
		G[a].push_back(b);
		G[b].push_back(a);

		c[a][b] = C;
	}

	fin.close();
}

void write()
{
	ofstream fout("maxflow.out");

	fout << max_flow << '\n';

	fout.close();
}