Cod sursa(job #3155258)

Utilizator IanisBelu Ianis Ianis Data 7 octombrie 2023 19:10:19
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.24 kb
#pragma GCC optimize("Ofast,unroll-loops")
#include <bits/stdc++.h>

#define sz(a) ((int)(a).size())
#define all(a) (a).begin(), (a).end()

#define fi first
#define se second

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;
	}
};

#ifdef LOCAL
InParser fin("input.txt");
#define fout cout
#else
#define FILE_NAME "maxflow"
InParser fin(FILE_NAME ".in");
ofstream fout(FILE_NAME ".out");
#define endl '\n'
#endif

typedef long long ll;
typedef pair<int, int> pii;

const int NMAX = 1005;
const int INF = 2e9+5;

int n, m;
int g[NMAX][NMAX];
int d[NMAX];
int last[NMAX];

void read() {
	fin >> n >> m;
	for (int i = 1, x, y, c; i <= m; i++) {
		fin >> x >> y >> c;
		g[x][y] = c;
	}
}

bool bfs() { 
	memset(d, 0, sizeof(d));
	for (int i = 1; i <= n; i++) last[i] = 1;

	queue<int> q;
	q.push(1);

	while (!q.empty()) {
		int u = q.front();
		q.pop();
		if (u == n) continue;
		for (int i = 2; i <= n; i++) {
			if (!d[i] && g[u][i] > 0) {
				d[i] = d[u] + 1;
				q.push(i);
			}
		}
	}

	return d[n];
}

int dfs(int x, int flow) {
	if (x == n) return flow;

	for (; last[x] <= n; last[x]++) {
		int i = last[x];
		if (g[x][i] > 0 && d[i] == d[x] + 1) {
			if (int ret = dfs(i, min(flow, g[x][i]))) {
				g[x][i] -= ret;
				g[i][x] += ret;
				return ret;
			}
		}
	}

	return 0;
}

int dinic() {
	int max_flow = 0;
	while (bfs()) {
		while (int flow = dfs(1, INF))
			max_flow += flow;
	}
	return max_flow;
}

signed main() {
	read();
	fout << dinic() << endl;
	return 0;
}