Cod sursa(job #2025742)

Utilizator horiainfoTurcuman Horia horiainfo Data 23 septembrie 2017 10:43:00
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.36 kb
#include <iostream>
#include <queue>
#include <vector>
#include <cstring>

#define N 1001
#define INF 550000001 
using namespace std;

int n, m;
vector<int> G[N];
int C[N][N], flow[N][N];
int ant[N];
bool viz[N];

bool BFS(){

	queue<int> que;
	que.push(1);
	memset(viz, 0, sizeof(viz));
	viz[1] = 1;

	while(!que.empty()){

		int node = que.front();
		if(node == n) return 1;
		que.pop();

		for(auto next : G[node])
			if(!viz[next] && C[node][next] - flow[node][next] != 0){

				viz[next] = 1;
				ant[next] = node;
				que.push(next);
			}
	}
	return 0;
}

int main(){

	freopen("maxflow.in", "r", stdin);
	freopen("maxflow.out", "w", stdout);
	
	scanf("%d%d", &n, &m);
	for(int i = 1; i <= m; i ++){

		int x, y, c;
		scanf("%d%d%d", &x, &y, &c);
		G[x].push_back(y);
		G[y].push_back(x);

		C[x][y] = c;
	}

	int maxFlow = 0;
	while(BFS())
		for(auto next : G[n])
			if(viz[next] && C[next][n] - flow[next][n] != 0){
			
				int node = n, fmin = INF;
				ant[n] = next;
				while(node != 1)
					fmin = min(fmin, C[ant[node]][node] - flow[ant[node]][node]),
					node = ant[node];

				if(fmin == 0)	continue;
				node = n;
				while(node != 1)
					flow[ant[node]][node] += fmin,
					flow[node][ant[node]] -= fmin,
					node = ant[node];

				maxFlow += fmin;
			}

	printf("%d", maxFlow);
	return 0;
}