Cod sursa(job #1417025)

Utilizator theprdvtheprdv theprdv Data 9 aprilie 2015 13:59:25
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.6 kb
#include <fstream>
#include <queue>
#include <algorithm>
#include <vector>
#include <cstring>

using namespace std;

fstream fin("maxflow.in", ios::in);
fstream fout("maxflow.out", ios::out);

#define s second
#define f first
#define MAXN 1005
pair<int, int> NT[MAXN][MAXN];
vector <int> ways, list[MAXN];
int N, M, used[MAXN], p[MAXN], flow;

inline void read()
{
	fin >> N >> M;
	for (int i = 1, x, y, c; i <= M; i++){
		fin >> x >> y >> c;
		NT[x][y].s = c;
		list[x].push_back(y);
		list[y].push_back(x);
		if (y == N) ways.push_back(x);
	}
	fin.close();
}
void BFS()
{
	used[N] = 1;
	memset(used + 2, 0, sizeof(int) * N);
	queue <int> q;
	q.push(1);

	while (!q.empty()){
		int node = q.front();
		q.pop();
		if (node == N) continue;

		for (int i = 0, size = list[node].size(), next; i < size; i++){
			next = list[node][i];
			if (!used[next] && NT[node][next].s - NT[node][next].f)
				q.push(next),
				used[next] = 1,
				p[next] = node;
		}
	}
}

int main()
{
	read();
	used[1] = 1;

	while (true){
		BFS();
		if (!used[N]) break;
		int m_flow;

		for (int i = 0, node; i < (int)ways.size(); i++){
			p[N] = ways[i];
			if (!used[p[N]] || NT[p[N]][N].s - NT[p[N]][N].f < 1) continue;

			for (node = N, m_flow = ~(1 << 31); node != 1; node = p[node])
				m_flow = min(m_flow, NT[p[node]][node].s - NT[p[node]][node].f);

			if (!m_flow)  continue;
			for (node = N; node != 1; node = p[node])
				NT[p[node]][node].f += m_flow,
				NT[node][p[node]].f -= m_flow;
					
			flow += m_flow;
		}
	}
	fout << flow << "\n";

	fout.close();
	return 0;
}