Pagini recente » Cod sursa (job #480212) | Cod sursa (job #307015) | Cod sursa (job #2683609) | Cod sursa (job #2578859) | Cod sursa (job #2884317)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream f ("maxflow.in");
ofstream g ("maxflow.out");
const long long INF = __LONG_LONG_MAX__;
long long n;
long long capacity[501][501];
vector <long long> adj[10001];
long long bfs(long long s, long long t, vector<long long>& parent) {
fill(parent.begin(), parent.end(), -1);
parent[s] = -2;
queue<pair<long long, long long>> q;
q.push({s, INF});
while (!q.empty()) {
long long cur = q.front().first;
long long flow = q.front().second;
q.pop();
for (long long next : adj[cur]) {
if (parent[next] == -1 && capacity[cur][next]) {
parent[next] = cur;
long long new_flow = min(flow, capacity[cur][next]);
if (next == t)
return new_flow;
q.push({next, new_flow});
}
}
}
return 0;
}
long long maxflow(long long s, long long t) {
long long flow = 0;
vector<long long> parent(n + 1);
long long new_flow;
while (new_flow = bfs(s, t, parent)) {
flow += new_flow;
long long cur = t;
while (cur != s) {
long long prev = parent[cur];
capacity[prev][cur] -= new_flow;
capacity[cur][prev] += new_flow;
cur = prev;
}
}
return flow;
}
void Read()
{
long long m;
f >> n >> m;
long long x, y, z;
for (long long i = 1; i <= m; i++)
{
f >> x >> y >> z;
adj[x].push_back(y);
capacity[x][y] = z;
}
}
int main()
{
Read();
long long flow = maxflow(1, 4);
if (flow == 0)
{
g << "Apa nu ajunge!";
}
else
{
g << flow;
}
}