Cod sursa(job #2722743)

Utilizator ViAlexVisan Alexandru ViAlex Data 13 martie 2021 11:42:22
Problema Flux maxim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.23 kb
#include<iostream>
#include<fstream>
#include<vector>
#include<cstring>
#include<map>
#include<algorithm>
#include<set>
#include<deque>
#include<queue>

using namespace std;
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");

const int mx=2000;
const int inf=2e9;

struct edge{
	int dest,cap; 
};
struct node{
	int index,flow;
};

int n,m;
int flow[mx][mx],parent[mx];

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

int bfs(){
	for(int i=1;i<=n;i++)
		parent[i]=-1;

	deque<node> nodes;	
	nodes.push_back({1,inf});
	parent[1]=0;

	bool found=false;
	int ans;

	while(nodes.size()){
		node here=nodes.front();
		nodes.pop_front();

		if(here.index==n){
			found=true;
			ans=here.flow;
			break;
		}

		for(int i=1;i<=n;i++){
			if(parent[i]==-1 && flow[here.index][i]!=0){
				parent[i]=here.index;	
				nodes.push_back({i,min(here.flow,flow[here.index][i])});
			}
		}
	}

	if(!found)
		return 0;

	int here=n,previous;
	while(here!=1){
		previous=parent[here];
		flow[previous][here]-=ans;
		flow[here][previous]+=ans;
		here=previous;
	}
	return ans;

}

void solve(){
	int f,total=0;
	while((f=bfs())){
		total+=f;
	}
	cout<<total;
}


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