Cod sursa(job #2621153)

Utilizator ViAlexVisan Alexandru ViAlex Data 30 mai 2020 12:55:05
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.42 kb
#include<bits/stdc++.h>
using namespace std;


ifstream in("maxflow.in");
ofstream out("maxflow.out");
#define MAXNODES 1000

int num_nodes,num_edges;
int capacity[MAXNODES][MAXNODES];
vector<int> graph[MAXNODES];


bool visited[MAXNODES];
int previous[MAXNODES];

int sink;

void read(){
	in>>num_nodes>>num_edges;
	sink=num_nodes-1;
	int a,b,c;
	for(int i=0;i<num_edges;i++){
		in>>a>>b>>c;
		graph[a-1].push_back(b-1);
		graph[b-1].push_back(a-1);
		capacity[a-1][b-1]=c;
	}
	memset(previous,-1,1000*sizeof(int));
}


bool bfs(){
	memset(visited,false,1000*sizeof(bool));

	deque<int> nodes;
	nodes.push_back(0);
	visited[0]=true;

	while(nodes.size()){
		int here=nodes.front();
		nodes.pop_front();
		if(here!=sink){

			for(int next:graph[here]){
				if(!visited[next] && capacity[here][next]>0){
					visited[next]=true;
					previous[next]=here;
					nodes.push_back(next);
				}
			}
		}
	}
	return visited[sink];
}


void solve(){

	int maxflux=0;
	while(bfs()){
		for(int node:graph[sink]){
			int here=sink,minremaining=1e9;
			previous[sink]=node;
			while(previous[here]!=-1){	
				minremaining=min(minremaining,capacity[previous[here]][here]);
				here=previous[here];
			}
			here=sink;
			while(previous[here]!=-1){
				capacity[previous[here]][here]-=minremaining;
				capacity[here][previous[here]]+=minremaining;
				here=previous[here];
			}
			maxflux+=minremaining;
		}
	}
	out<<maxflux;
}



int main(){
	read();
	solve();
}