Cod sursa(job #1309170)

Utilizator CosminRusuCosmin Rusu CosminRusu Data 5 ianuarie 2015 14:47:56
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.57 kb
#include <fstream>
#include <iostream>
#include <cstring>
#include <bitset>
#include <vector>
#include <queue>

using namespace std;

const int maxn = 1005;
const int oo = 0x3f3f3f3f;

int n, m, father[maxn], c[maxn][maxn], f[maxn][maxn];
vector <int> g[maxn];
bitset <maxn> used;
queue <int> q;

inline bool bfs(int source, int sink) {
	used.reset();
	used[source] = 1;
	q.push(source);
	while(!q.empty()) {
		int node = q.front();
		q.pop();
		if(node == sink)
			continue;
		for(vector <int> :: iterator it = g[node].begin() ; it != g[node].end() ; ++ it) {
			if(!used[*it] && c[node][*it] - f[node][*it] > 0) {
				used[*it] = 1;
				father[*it] = node;
				q.push(*it);
			}
		}
	}
	return used[sink];
}

inline int getmaxflow(int source, int sink) {
	int maxflow = 0;
	while(bfs(source, sink)) {
		for(vector <int> :: iterator it = g[sink].begin(), fin = g[sink].end() ; it != fin ; ++ it) {
			if(c[*it][sink] - f[*it][sink] <= 0 || !used[*it])
				continue;
			father[sink] = *it;
			int bottleneck = oo;
			for(int i = sink ; i != source ; i = father[i])
				bottleneck = min(bottleneck, c[father[i]][i] - f[father[i]][i]);
			if(!bottleneck)
				continue;
			for(int i = sink ; i != source ; i = father[i]) {
				f[father[i]][i] += bottleneck;
				f[i][father[i]] -= bottleneck;
			}
			maxflow += bottleneck;
		}
	}
	return maxflow;
}

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

	fin >> n >> m;
	for(int i = 1 ; i <= m ; ++ i) {
		int x, y, z;
		fin >> x >> y >> z;
		c[x][y] += z;
		g[x].push_back(y);
		g[y].push_back(x);
	}
	fout << getmaxflow(1, n) << '\n';
}