Cod sursa(job #1548076)

Utilizator kassay_akosKassay Akos kassay_akos Data 10 decembrie 2015 14:10:22
Problema Flux maxim Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.64 kb
#include <iostream>
#include <fstream>
#include <string.h>
#include <vector>
#include <queue>
#include <algorithm>

using namespace std;
const int nmax = 5;							// 1003;
vector < int > v[nmax];
int cost[nmax][nmax], n, m;
int used[nmax][nmax];
int Q[5 * nmax], father[nmax],vis[nmax];

bool BFS();

int main(){
	freopen("maxflow.in", "r", stdin);
	freopen("maxflow.out", "w", stdout);
	memset(cost, 0, sizeof(cost));
	memset(used, 0, sizeof(cost));

	scanf("%d %d", &n, &m);
	int x, y, c;
	for (; m--;){
		scanf("%d %d %d", &x, &y, &c);
		v[x].push_back(y);
		cost[x][y] = c;
		if (y == n) v[n].push_back(x);				// its ganna be inverted the Nth line
	}

	int maxflow = 0,nod,fmin;
	while (BFS()){
		for (int i = 0; i < v[n].size(); i++){
			nod = v[n][i];
			if (cost[nod][n] - used[nod][n] == 0) continue;
			fmin = cost[nod][n] - used[nod][n];
			for (; nod != 1; nod = father[nod])
				fmin = min(fmin, cost[father[nod]][nod] - used[father[nod]][nod]);
			
			nod = v[n][i];
			maxflow += fmin;
			used[nod][n] += fmin;
			for (; nod != 1; nod = father[nod])
				used[father[nod]][nod] += fmin;
		}
	}

	
	printf("%d ", maxflow);
	fclose(stdin);
	fclose(stdout);
	return 0;
}


bool BFS(){
	int nod;
	memset(father, 0, 4 * (n + 2));
	memset(vis   , 0, 4 * (n + 2));
	Q[0] = 1;		// len
	Q[1] = 1;

	for (int i = 1; i <= Q[0]; i++) {
		nod = Q[i];
		if (nod == n) continue;
		for (int j = 0; j < v[nod].size(); j++) {
			int endP = v[nod][j];
			if (cost[nod][endP] - used[nod][endP] > 0 && !vis[endP]) {
				Q[++Q[0]] = endP;
				father[endP] = nod;
				vis[endP] = 1;
			}
		}
	}
	return vis[n];
}