Pagini recente » Cod sursa (job #3159087) | Cod sursa (job #745153) | Cod sursa (job #698136) | Cod sursa (job #2033232) | Cod sursa (job #1454548)
#include <fstream>
#include <vector>
#include <queue>
#include <cstring>
#define maxn 1030
#define inf 1<<30
using namespace std;
int n, m;
bool viz[maxn];
int parent[maxn];
vector< int > graph[maxn];
int cost[maxn][maxn];
int residualGraph[maxn][maxn];
int min(int a, int b)
{
if (a < b)
return a;
return b;
}
bool bfs()
{
memset(viz, 0, sizeof(viz));
queue<int> q;
q.push(1);
viz[1] = true;
while (!q.empty())
{
int nod = q.front();
q.pop();
for (int i = 0; i < graph[nod].size(); i++)
{
int v = graph[nod][i];
if (!viz[v] && residualGraph[nod][v] != cost[nod][v])
{
q.push(v);
parent[v] = nod;
viz[v] = true;
}
}
}
return viz[n];
}
int edmondsKarp()
{
int max_flow = 0;
while (true)
{
//caut o cale nesaturata
if (!bfs())
break;
int path_flow = inf;
//gasesc minimul de pe aceasta cale
for (int v = n; v != 1; v = parent[v])
{
int u = parent[v];
path_flow = min(path_flow, cost[u][v] - residualGraph[u][v]);
}
if (path_flow == 0)
continue;
for (int v = n; v != 1; v = parent[v])
{
int u = parent[v];
residualGraph[u][v] += path_flow;
residualGraph[v][u] -= path_flow;
}
max_flow += path_flow;
}
return max_flow;
}
int main()
{
ifstream in("maxflow.in");
ofstream out("maxflow.out");
in >> n >> m;
int x, y, z;
for (int i = 0; i < m; i++)
{
in >> x >> y >> z;
graph[x].push_back(y);
graph[y].push_back(x);
cost[x][y] = z;
}
out << edmondsKarp();
}