Cod sursa(job #3153198)

Utilizator tryharderulbrebenel mihnea stefan tryharderul Data 28 septembrie 2023 16:35:18
Problema Flux maxim Scor 60
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.35 kb
#include <bits/stdc++.h>

using namespace std;

const int NMAX = 1001;

int n, m;
int parent[NMAX];
int g[NMAX][NMAX];

void bfs(int start) {
	queue<int> q;
	q.push(start);
	while(!q.empty()) {
		int node = q.front();
		q.pop();
		for(int son = 0; son < n; son++) {
			int w = g[node][son];
			if(w <= 0 || parent[son] != -1) continue ;
			parent[son] = node;
			q.push(son);
		}
	}
}

int flow(int source, int sink) {
	bool STOP = false;
	int flow = 0;
	while(!STOP) {
		memset(parent, -1, size(parent));
		STOP = true;
		bfs(source);
		if(parent[sink] != -1) { 
			STOP = false;
			for(int son = 0; son < n; son++) {
				if(g[son][sink] <= 0 || parent[son] == -1) continue;
				int node = son, curr_flow = g[son][sink]; 
				while(node != source) {
					curr_flow = min(curr_flow, g[parent[node]][node]);
					node = parent[node];
				}
				node = son;
				g[son][sink] -= curr_flow;
				g[sink][son] += curr_flow;
				while(node != source) {
					g[parent[node]][node] -= curr_flow;
					g[node][parent[node]] += curr_flow;
					node = parent[node];
				}			
				flow += curr_flow;				
			}
	
		}
	}
	return flow;
}

int main() {
	freopen("maxflow.in", "r", stdin);
	freopen("maxflow.out", "w", stdout);
	scanf("%d %d", &n, &m);
	for(int i = 0; i < m; i++) {
		int x, y, c;
		scanf("%d %d %d", &x, &y, &c);
		x--, y--;
		g[x][y] = c;
	}

	printf("%d\n", flow(0, n-1));

	return 0;
}