Pagini recente » Cod sursa (job #3189888) | Cod sursa (job #2066113) | Cod sursa (job #2691812) | Cod sursa (job #3131751) | Cod sursa (job #3260351)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");
const int dim = 1002;
int n, flux[dim][dim], capacitate[dim][dim], tata[dim], max_flow;
bool viz[dim];
vector<int> a[dim];
queue<int>coada;
bool bfs (int sursa, int dest)
{
for (int i = 1; i <= n; i++)
viz[i] = 0;
coada.push(sursa);
tata[sursa] = 0;
viz[sursa] = 1;
while (!coada.empty())
{
int x = coada.front();
coada.pop();
for (int y : a[x])
if (!viz[y] && capacitate[x][y] - flux[x][y] > 0)
{
coada.push(y);
viz[y] = 1;
tata[y] = x;
}
}
if (!viz[dest])
return 0; ///nu am gasit drum sursa->dest
int x = dest, minim = INT_MAX;
vector<int>w;
while (x != 0)
{
///reconstuim drumul
w.push_back(x);
x = tata[x];
}
reverse(w.begin(), w.end());
for (int i = 0; i < w.size() - 1; i++)
{
///w[i] ---> w[i+1]
minim = min(minim, capacitate[w[i]][w[i+1]] - flux[w[i]][w[i+1]]);
}
for (int i = 0; i < w.size() - 1; i++)
{
flux[w[i]][w[i+1]] += minim;
flux[w[i+1]][w[i]] -= minim;
}
///fout << minim<<endl;
max_flow += minim;
return 1;
}
int main()
{
int m, x, y, z, ok = 1;
fin >> n >> m;
while (m--)
{
fin >> x >> y >> z;
capacitate[x][y]=z;
a[x].push_back(y);
a[y].push_back(x);
}
do
{
ok = bfs(1, n);
}while (ok);
fout << max_flow;
return 0;
}