Cod sursa(job #3002025)

Utilizator FunnyStockyMihnea Andreescu FunnyStocky Data 14 martie 2023 11:43:40
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.5 kb
#include <cmath>
#include <functional>
#include <fstream>
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <set>
#include <map>
#include <list>
#include <time.h>
#include <math.h>
#include <random>
#include <deque>
#include <cassert>
#include <queue>
#include <unordered_map>
#include <unordered_set>
#include <iomanip>
#include <bitset>
#include <sstream>
#include <chrono>
#include <cstring>
#include <numeric>

using namespace std;

struct Flow
{
	const int INF = (int)1e9 + 7;
	int n;
	struct Edge
	{
		int to, cap;
	};
	vector<Edge> edges;
	vector<vector<int>> g;
	vector<int> lvl, ptr;

	void init(int nn)
	{
		n = nn;
		assert(n >= 1);

		edges.clear();
		g.clear();
		lvl.clear();
		ptr.clear();

		g.resize(n);
		lvl.resize(n);
		ptr.resize(n);
	}

	void addedge(int a, int b, int c)
	{
		a--;
		b--;
		assert(0 <= a && a < n);
		assert(0 <= b && b < n);
		edges.push_back({ b, c });
		edges.push_back({ a, 0 });
		g[a].push_back((int)edges.size() - 2);
		g[b].push_back((int)edges.size() - 1);
	}

	int dfs(int a, int cur)
	{
		if (a == n - 1 || cur == 0) return cur;
		while (ptr[a] < (int)g[a].size())
		{
			int i = g[a][ptr[a]++];
			if (lvl[edges[i].to] == 1 + lvl[a] && edges[i].cap > 0)
			{
				int what = dfs(edges[i].to, min(cur, edges[i].cap));
				if (what)
				{
					ptr[a]--;
					edges[i].cap -= what;
					edges[i ^ 1].cap += what;
					return what;
				}
			}
		}
		return 0;
	}

	int maxflow()
	{
		int sol = 0;
		while (1)
		{
			for (int i = 0; i < n; i++) lvl[i] = -1, ptr[i] = 0;
			queue<int> q;
			q.push(0);
			lvl[0] = 0;
			while (!q.empty())
			{
				int a = q.front();
				q.pop();
				for (auto& i : g[a])
				{
					int b = edges[i].to;
					if (edges[i].cap > 0 && lvl[b] == -1)
					{
						lvl[b] = 1 + lvl[a];
						q.push(b);
					}
				}
			}
			if (lvl[n - 1] == -1) break;
			int init = sol;
			while (1)
			{
				int now = dfs(0, INF);
				if (now == 0) break;
				sol += now;
			}
		}
		return sol;
	}
};

signed main()
{
#ifdef ONPC	
	FILE* stream;
	freopen_s(&stream, "input.txt", "r", stdin);
#else
	ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
	freopen("maxflow.in", "r", stdin);
	freopen("maxflow.out", "w", stdout);
#endif

	int n, m;
	cin >> n >> m;
	Flow f;
	f.init(n);
	for (int i = 1; i <= m; i++)
	{
		int a, b, c;
		cin >> a >> b >> c;
		f.addedge(a, b, c);
	}
	cout << f.maxflow() << "\n";
	return 0;
}