Cod sursa(job #1954394)

Utilizator DoubleNyNinicu Cristian DoubleNy Data 5 aprilie 2017 13:03:03
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.42 kb
#include <bits/stdc++.h>
using namespace std; 

int n,m;
int flow[1234][1234];
int parent[1234];
bool visited[1234];
int maxFlow;
vector <int> adj[1234];
bool BFS(){
		memset(visited, 0, sizeof(visited));
		queue <int> que;
		que.push(1);
		visited[1] = 1;
		while(!que.empty()){
			int node = que.front(); 
			que.pop();
			if(node == n)
				return(true);
			for(unsigned i=0;i<adj[node].size(); i++){
				if(!visited[adj[node][i]] && flow[node][adj[node][i]]){
					visited[adj[node][i]] = true;
					que.push(adj[node][i]);
					parent[adj[node][i]] = node;
				}
			}
		}
		return(false);
}

int main(){
			freopen ("maxflow.in", "r", stdin);
			freopen ("maxflow.out", "w", stdout);
			scanf("%d%d", &n,&m);
			for(int i = 0; i < m; i++){
					int x,y,volume;
					scanf("%d%d%d", &x, &y, &volume);
					adj[x].push_back(y);
					adj[y].push_back(x);
					flow[x][y] += volume;
			}
			
			while( BFS() ){
					int current;
					for(unsigned i=0; i<adj[n].size(); i++){
							if(!visited[adj[n][i]] || flow[adj[n][i]][n] == 0)
								continue;
							parent[n] = adj[n][i];
							current = 1e9;
							for(int node=n; node != 1; node = parent[node])
								current = min(current, flow[parent[node]][node]);
							maxFlow += current;
							for (int node = n; node != 1; node = parent[node]){
								flow[parent[node]][node] -= current;
								flow[node][parent[node]] += current;
								
							}
					}
			}
			printf("%d\n", maxFlow);
}