Pagini recente » Cod sursa (job #811745) | Cod sursa (job #2390556) | Cod sursa (job #534427) | Cod sursa (job #3359540) | Cod sursa (job #3359531)
#pragma GCC optimize("Ofast")
// #pragma GCC target("avx2")
#include <bits/stdc++.h>
using namespace std;
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");
typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
const int N = 1e3 + 5;
const int M = 1e4 + 5;
int n, m;
struct MaxFlow
{
int n, m;
queue<int> q;
vector<int> ad[N];
int p[N], d[N], minnod[N];
pair<int, int> cap[M];
int sursa, destinatie;
void AddEdge(int x, int y, int c)
{
m++;
cap[2 * m] = {0, x};
cap[2 * m + 1] = {c, y};
ad[y].push_back(2 * m);
ad[x].push_back(2 * m + 1);
}
bool BFS()
{
for (int i = 1; i <= n; i++)
minnod[i] = 1e9;
for (int i = 1; i <= n; i++)
d[i] = 1e9;
q.push(sursa);
d[sursa] = 0;
while (!q.empty())
{
int i = q.front();
q.pop();
for (int x : ad[i])
if (cap[x].first > 0 && (d[cap[x].second] > d[i] + 1 ||
(d[cap[x].second] > d[i] + 1 && min(minnod[cap[x].second], cap[x].first) > minnod[i])))
{
d[cap[x].second] = d[i] + 1;
minnod[cap[x].second] = min(minnod[cap[x].second], cap[x].first);
q.push(cap[x].second);
p[cap[x].second] = x;
}
}
return d[destinatie] != 1e9;
}
int Saturate()
{
int minn = INT_MAX;
int copyDest = destinatie;
while (copyDest != sursa)
{
minn = min(minn, cap[p[copyDest]].first);
copyDest = cap[p[copyDest] ^ 1].second;
}
copyDest = destinatie;
while (copyDest != sursa)
{
cap[p[copyDest]].first -= minn;
cap[p[copyDest] ^ 1].first += minn;
copyDest = cap[p[copyDest] ^ 1].second;
}
return minn;
}
int Solve()
{
int ans = 0;
while (BFS())
{
ans += Saturate();
}
return ans;
}
MaxFlow(int s, int d, int _n)
{
m = 0;
n = _n;
sursa = s;
destinatie = d;
memset(cap, 0, sizeof(cap));
}
};
signed main()
{
fin >> n >> m;
MaxFlow flow(1, n, n);
while (m--)
{
int x, y, c;
fin >> x >> y >> c;
flow.AddEdge(x, y, c);
}
fout << flow.Solve();
return 0;
}