Cod sursa(job #1982974)

Utilizator SlevySlevoaca Stefan-Gabriel Slevy Data 20 mai 2017 19:58:32
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.83 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <bitset>
#define NMAX 1001
#define oo (1 << 30)
#define min(x, y) ((x < y) ? x : y) 

using namespace std;

vector<int> G[NMAX];
int n, flow[NMAX][NMAX], cap[NMAX][NMAX], father[NMAX];
queue<int> q;
bitset<NMAX> mark;

void read() {

	int m, x, y, c;
	ifstream in("maxflow.in");
	in >> n >> m;
	for (int i = 1; i <= m; i++) {

		in >> x >> y >> c;
		G[x].push_back(y);
		G[y].push_back(x);
		cap[x][y] = c;
	}
	in.close();
}

void bfs(int start) {

	mark.reset();
	q.push(start);
	mark.set(start);
	father[start] = 0;

	unsigned int node;

	while (!q.empty()) {

		node = q.front();

		for (unsigned int i = 0; i < G[node].size(); i++) 
			if (!mark.test(G[node][i]) && cap[node][G[node][i]] > flow[node][G[node][i]]) {

				q.push(G[node][i]);
				mark.set(G[node][i]);
				father[G[node][i]] = node;
			}

		q.pop();
	}
}

int main() {
	
	read();

	unsigned int node = 0, val;
	unsigned int max_flow = 0;

	for (bfs(1); mark.test(n); bfs(1)) {

		for (unsigned int i = 0; i < G[n].size(); i++)
			if (mark.test(G[n][i]) && cap[G[n][i]][n] > flow[G[n][i]][n]) {

				node = G[n][i];
				val = oo;

				while (node != 0)
				{
					if (father[node] != 0)
						val = min(val, cap[father[node]][node] - flow[father[node]][node]);
					node = father[node];
				}

				node = G[n][i];
				val = min(val, cap[G[n][i]][n] - flow[G[n][i]][n]);
				max_flow += val;

				while (node != 0)
				{
					if (father[node] != 0) {

						flow[father[node]][node] += val;
						flow[node][father[node]] -= val;
					}
					node = father[node];
				}

				flow[G[n][i]][n] += val;
				flow[n][G[n][i]] -= val;

			}
	}

	ofstream out("maxflow.out");
	out << max_flow << "\n";
	out.close();
	return 0;
}