Cod sursa(job #2784207)

Utilizator dahaandreiDaha Andrei Codrin dahaandrei Data 16 octombrie 2021 02:47:06
Problema Flux maxim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.54 kb
#include <bits/stdc++.h>

using namespace std;

class InParser {
private:
	FILE *fin;
	char *buff;
	int sp;
	
 
	char read_ch() {
		++sp;
		if (sp == 4096) {
			sp = 0;
			fread(buff, 1, 4096, fin);
		}
		return buff[sp];
	}	
 
public:
	InParser(const char* nume) {
		fin = fopen(nume, "r");
		buff = new char[4096]();
		sp = 4095;
	}
	
	InParser& operator >> (int &n) {
		char c;
		while (!isdigit(c = read_ch()) && c != '-');
		int sgn = 1;
		if (c == '-') {
			n = 0;
			sgn = -1;
		} else {
			n = c - '0';
		}
		while (isdigit(c = read_ch())) {
			n = 10 * n + c - '0';
		}
		n *= sgn;
		return *this;
	}
	
	
	
	InParser& operator >> (long long &n) {
		char c;
		n = 0;
		while (!isdigit(c = read_ch()) && c != '-');
		long long sgn = 1;
		if (c == '-') {
			n = 0;
			sgn = -1;
		} else {
			n = c - '0';
		}
		while (isdigit(c = read_ch())) {
			n = 10 * n + c - '0';
		}
		n *= sgn;
		return *this;
	}
};


ofstream out("maxflow.out");

const int MAXN = 1e3;
const int MAXM = 5e3;

// struct Edge {
// 	int next;
// 	int capacity;
// 	int flow;
// 	int rev;

// 	Edge(int _next, int _capacity, int _flow, int _rev) {
// 		next = _next;
// 		capacity = _capacity;
// 		flow = _flow;
// 		rev = _rev;
// 	}
// };

int n, m;

vector< int > g[MAXN + 2];
int flow[MAXN + 2][MAXN + 2];
int capacity[MAXN + 2][MAXN + 2];
int depth[MAXN + 2];

bool bfs() {	
	queue<int> q;
	memset(depth, 0, sizeof(depth));
	depth[1] = 1;

	q.push(1);
	int cur;
	while (q.size()) {
		cur = q.front();
		q.pop();

		for (auto &x : g[cur]) {
			if (x == n)
				reachedSink = true;
			if (depth[x] == 0  && capacity[cur][x] > flow[cur][x]) {
				depth[x] = depth[cur] + 1;
				q.push(x);
			}
		}
	}

	return depth[n];
}


int dfs(int cur, int fflow) {
	if (cur == n)
		return fflow;

	for (auto &x : g[cur]) {
		if (depth[x] == depth[cur] + 1 && capacity[cur][x] - flow[cur][x] > 0) {
			int tmpFlow = dfs(x, min(fflow, capacity[cur][x] - flow[cur][x]));
			if (tmpFlow > 0) {
				flow[cur][x] += tmpFlow;
				flow[x][cur] -= tmpFlow;
				return tmpFlow;
			}
		}
	}

	return 0;
}

int main() {
	InParser in("maxflow.in");

	in >> n >> m;

	for (int i = 0; i < m; ++ i) {
		int x, y, z;
		in >> x >> y >> z;
		g[x].push_back(y);
		g[y].push_back(x);
		capacity[x][y] = z;
	}


	int maxFlow = 0;

	while (bfs()) {
		int tmpFlow = 0;
		do {
			tmpFlow = dfs(1, 2e9);
			maxFlow += tmpFlow;
		} while (tmpFlow > 0);
	}

	out << maxFlow << '\n';

	return 0;
}