Pagini recente » Cod sursa (job #1482333) | Cod sursa (job #1894586) | Cod sursa (job #136647) | Cod sursa (job #70382) | Cod sursa (job #2967776)
#include <iostream>
#include <fstream>
#include <climits>
#include <vector>
#include <queue>
using namespace std;
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");
int N, M, s, f;
vector<int> tata;
vector<vector<int>> capacitate;
vector<vector<int>> LA;
bool bfs()
{
vector<bool> viz(N + 1);
queue<int> q;
q.push(s);
viz[s] = true;
tata[s] = -1;
while (!q.empty())
{
int u = q.front();
q.pop();
for (auto v : LA[u])
{
if (viz[v] == false && capacitate[u][v] != 0)
{
tata[v] = u;
if (v == f)
return true;
viz[v] = true;
q.push(v);
}
}
}
return false;
}
int EdmondsKarp()
{
long max_flow = 0;
while (bfs())
{
int u, v;
int path_flow = INT_MAX;
for (v = f; v != s; v = tata[v])
{
// gasesc flow ul necesar ca sa nu se creeze bottleneck
u = tata[v];
path_flow = min(path_flow, capacitate[u][v]);
}
for (v = f; v != s; v = tata[v])
{
u = tata[v];
capacitate[u][v] -= path_flow; // scad flowul gasit din capacitate pe arcele normale
capacitate[v][u] += path_flow; // adun flow ul gasit pe arcele reverse
}
max_flow += path_flow; // adaug flowul gasit la total
}
return max_flow;
}
int main()
{
fin >> N >> M;
s = 1;
f = N;
LA.resize(N + 1);
tata.resize(N + 1);
capacitate.resize(N + 1, vector<int>(N + 1));
for (int i = 1; i <= M; i++)
{
int u, v;
long c;
fin >> u >> v >> c;
LA[u].push_back(v);
LA[v].push_back(u);
capacitate[u][v] = c;
}
fout << EdmondsKarp();
return 0;
}