Cod sursa(job #2621079)

Utilizator ViAlexVisan Alexandru ViAlex Data 30 mai 2020 12:25:56
Problema Flux maxim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.44 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];
int flux[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;
	}
}


bool bfs(){
	memset(visited,false,1000*sizeof(bool));
	memset(previous,-1,1000*sizeof(int));
	deque<int> nodes;
	nodes.push_back(0);
	visited[0]=true;
	
	while(nodes.size()){
		int here=nodes.front();
		nodes.pop_front();

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


void solve(){
	int maxflux=0;
	while(bfs()){
		int here=sink,minremaining=1e9,remaining;
		while(previous[here]!=-1){	
			remaining=capacity[previous[here]][here]-flux[previous[here]][here];
			minremaining=min(minremaining,remaining);
			here=previous[here];
		}
		here=sink;
		while(previous[here]!=-1){	
			flux[previous[here]][here]+=minremaining;
			flux[here][previous[here]]-=minremaining;
			here=previous[here];
		}
		maxflux+=minremaining;
	}
	out<<maxflux;
}



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