Cod sursa(job #2955344)

Utilizator ViAlexVisan Alexandru ViAlex Data 16 decembrie 2022 19:32:30
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.25 kb
#include<iostream>
#include<fstream>
#include<vector>
#include<queue>
using namespace std;

ifstream in("maxflow.in");
ofstream out("maxflow.out");

const int mx = 1020;
const long long inf = 1e18;

long long capacity[mx][mx];
int n,m;
vector<int> g[mx];
vector<int> prv;

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

bool flow(){
	int s = 1, t = n;
	prv = vector<int>(n+1,-1);
	queue<int> q;
	q.push(s);
	while(!q.empty()){
		int here = q.front();
		q.pop();

		if(here == t){
			continue;
		}

		for(int k:g[here]){
			if(prv[k]!=-1 || capacity[here][k]==0)
				continue;
			prv[k] = here;
			q.push(k);
		}
	}
	return prv[t] != -1;
}


void solve(){
	int s = 1, t =n;
	long long total_flow = 0;

	while(flow()){
		for(int k : g[t]){
			if(capacity[k][t] == 0 || prv[k]==-1)
				continue;
			prv[t] = k;

			long long curflow = inf;
			int now = t;
			while(now != s){
				curflow = min(curflow , capacity[prv[now]][now]);
				now = prv[now];
			}
			now = t;
			while(now != s){
				capacity[prv[now]][now] -= curflow;
				capacity[now][prv[now]] += curflow;
				now = prv[now];
			}
			total_flow+=curflow;
		}	
	}
	out<<total_flow;
}

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