Pagini recente » Cod sursa (job #959284) | Cod sursa (job #1729395) | Cod sursa (job #2773792) | Cod sursa (job #2371815) | Cod sursa (job #2984155)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <cstring>
using namespace std;
ifstream f ("maxflow.in");
ofstream g ("maxflow.out");
const int SIZE = 1005;
const int INF = 0x3f3f3f3f;
int n, m;
int parent[SIZE];
int capacity[SIZE][SIZE];
vector <int> adj[SIZE];
void Read()
{
f >> n >> m;
for (int i = 1; i <= m; i++)
{
int x, y, z;
f >> x >> y >> z;
adj[x].push_back(y);
adj[y].push_back(x);
capacity[x][y] += z;
}
}
bool BFS(int s, int t)
{
memset(parent, 0, sizeof(parent));
queue <int> q;
q.push(s);
while (q.empty() == false)
{
int node = q.front();
q.pop();
for (unsigned int i = 0; i < adj[node].size(); i++)
{
int neighbour = adj[node][i];
if (parent[neighbour] == 0 && capacity[node][neighbour] > 0)
{
parent[neighbour] = node;
q.push(neighbour);
if (neighbour == t)
{
return true;
}
}
}
}
return false;
}
int MaxFlow(int s, int t)
{
int flow = 0;
while (BFS(1, n) == true)
{
for (unsigned int i = 0; i < adj[t].size(); i++)
{
int node = adj[t][i];
if (parent[node] == 0 || capacity[node][t] <= 0) continue;
parent[t] = node;
int newFlow = INF;
node = t;
while (node != s)
{
int par = parent[node];
newFlow = min(newFlow, capacity[par][node]);
node = par;
}
node = t;
while (node != s)
{
int par = parent[node];
capacity[par][node] -= newFlow;
capacity[node][par] += newFlow;
node = par;
}
flow += newFlow;
}
}
return flow;
}
int main()
{
Read();
g << MaxFlow(1, n);
return 0;
}