Cod sursa(job #2603468)

Utilizator mirceamaierean41Mircea Maierean mirceamaierean41 Data 20 aprilie 2020 01:23:19
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.28 kb
#include <fstream>
#include <vector>
#include <bitset>
#include <algorithm>
#include <queue>
using namespace std;

ifstream fin("maxflow.in");
ofstream fout("maxflow.out");

const int NMAX = 1005;

queue <int> q;

vector <int> g[NMAX];

int c[NMAX][NMAX], t[NMAX], n, m, x, y, z;

bitset <NMAX> viz;

bool BFS()
{
	viz.reset();
	q.push(1);
	viz[1] = 1;
	while (!q.empty())
	{
		x = q.front();
		q.pop();
		if (x == n)
			continue;
		for (size_t i = 0; i < g[x].size(); ++i)
			if (viz[g[x][i]] == 0 && c[x][g[x][i]] > 0)
			{
				viz[g[x][i]] = 1;
				q.push(g[x][i]);
				t[g[x][i]] = x;
			}
	}
	return viz[n];
}

int maxflow()
{
	int maxflow = 0;
	while (BFS())
	{
		for (size_t i = 0; i < g[n].size(); ++i)
		{
			y = g[n][i];
			if (!viz[y] || c[y][n] <= 0)
				continue;

			int e = 0x3f3f3f3f;
			t[n] = y;

			for (int j = n; j != 1; j = t[j])
				e = min(e, c[t[j]][j]);

			if (!e)
				continue;

			for (int j = n; j != 1; j = t[j])
			{
				c[t[j]][j] -= e;
				c[j][t[j]] += e;
			}
			maxflow += e;
		}
	}
	return maxflow;
}
int main()
{
	fin >> n >> m;
	while (m--)
	{
		fin >> x >> y >> z;
		g[x].push_back(y);
		g[y].push_back(x);
		c[x][y] = z;
	}
	fout << maxflow() << "\n";
	fout.close();
	return 0;
}