Cod sursa(job #3319260)

Utilizator CosminaneBoac Mihai Cosmin Cosminane Data 31 octombrie 2025 14:09:01
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.31 kb
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
vector <int> v[1005];
int cap[1005][1005], flow[1005][1005], f[1005], n;
bool bfs(){
	int i, x, y;
	for( i = 1; i <= n; i++ ){
		f[i] = INT32_MAX / 3;
	}
	f[1] = 0;
	queue <int> q;
	q.push( 1 );
	while( q.empty() == false ){
		x = q.front();
		q.pop();
		for( i = 0; i < v[x].size(); i++ ){
			y = v[x][i];
			if( flow[x][y] < cap[x][y] && f[x] + 1 < f[y] ){
				f[y] = f[x] + 1;
				q.push( y );
			}
		}
	}
	return f[n] != INT32_MAX / 3;
}
int maxflow( int x, int max_flow ){
	int i, y, tot_flow, curr_flow;
	if( max_flow == 0 ){
		return 0;
	}
	if( x == n ){
		return max_flow;
	}
	tot_flow = 0;
	for( i = 0; i < v[x].size(); i++ ){
		y = v[x][i];
		if( f[x] + 1 != f[y] ){
			continue;
		}
		curr_flow = maxflow( y, min( max_flow - tot_flow, cap[x][y] - flow[x][y] ) );
		flow[x][y] += curr_flow;
		flow[y][x] -= curr_flow;
		tot_flow += curr_flow;
	}
	return tot_flow;
}
int main() {
	int m, i, x, y, c, ras;
	ifstream fin( "maxflow.in" );
	ofstream fout( "maxflow.out" );
	fin >> n >> m;
	for( i = 0; i < m; i++ ){
		fin >> x >> y >> c;
		v[x].push_back( y );
		v[y].push_back( x );
		cap[x][y] += c;
	}
	ras = 0;
	while( bfs() ){
		ras += maxflow( 1, INT32_MAX / 3 );
	}
	fout << ras;
	return 0;
}