Cod sursa(job #2700788)

Utilizator ViAlexVisan Alexandru ViAlex Data 28 ianuarie 2021 20:02:47
Problema Flux maxim Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.47 kb
#include<iostream>
#include<fstream>
#include<vector>
#include<cstring>
#include<map>
#include<algorithm>
#include<set>
#include<deque>
#include<queue>

#define FAST cin.tie(NULL); ios_base::sync_with_stdio(false);
using namespace std;
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");


void init(){
	FAST
}


const int mx=1000;
vector<int> g[mx];
bool visited[mx];
int capacity[mx][mx],previous[mx];
int n,m;

void read(){
	int a,b,c;
	fin>>n>>m;
	for(int i=0;i<m;i++){
		fin>>a>>b>>c;
		a--;b--;
		g[a].push_back(b);
		g[b].push_back(a);
		capacity[a][b]=c;
		capacity[b][a]=0;
	}
	
}

int bfs(){
	memset(previous,-1,1000*sizeof(int));
	memset(visited,false,1000*sizeof(bool));

	deque<int> nodes;
	nodes.push_back(0);
	previous[0]=-1;
	visited[0]=true;
	
	while(nodes.size()){
		int here=nodes.front();			
		nodes.pop_front();

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


	int here=n-1;
	if(previous[here]==-1)
		return 0;

	int minimum=2e9;
	while(previous[here]!=-1){
		int prev=previous[here];
		minimum=min(minimum,capacity[prev][here]);
		here=prev;
	}
	
	here=n-1;
	while(previous[here]!=-1){
		int prev=previous[here];
		capacity[prev][here]-=minimum;
		capacity[here][prev]+=minimum;
		here=prev;
	}
	return minimum;	
}

void solve(){
	int flow=0,newflow;

	do{
		newflow=bfs();
		flow+=newflow;
	}
	while(newflow);
	fout<<flow;
}



int main(){
	init();
	read();
	solve();
	return 0;
}