Pagini recente » Cod sursa (job #826159) | Cod sursa (job #2268184) | Cod sursa (job #1415842) | Cod sursa (job #357015) | Cod sursa (job #2961122)
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
#include <climits>
#include <cstring>
using namespace std;
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");
int N, M;
vector <vector<int>> adj, capacity;
vector <int> parent;
int BFS(int start, int end)
{
vector <bool> vis(N + 1);
parent[start] = -1;
vis[start] = true;
queue <int> q;
q.push(start);
while (!q.empty())
{
int current = q.front();
q.pop();
for (int next : adj[current])
{
if (!vis[next] && capacity[current][next])
{
parent[next] = current;
if (next == end)
return true;
vis[next] = true;
q.push(next);
}
}
}
return false;
}
int MaxFlow(int start, int end)
{
long max_flow = 0;
while (BFS(start, end))
{
int flow = INT_MAX;
for (int node = end; node != start; node = parent[node])
flow = min(flow, capacity[parent[node]][node]);
for (int node = end; node != start; node = parent[node])
{
capacity[parent[node]][node] -= flow;
capacity[node][parent[node]] += flow;
}
max_flow += flow;
}
return max_flow;
}
int main()
{
fin >> N >> M;
int source = 1, dest = N;
adj.resize(N + 1);
parent.resize(N + 1);
capacity.resize(N + 1, vector <int>(N + 1));
while(M)
{
int x, y, cap;
fin >> x >> y >> cap;
capacity[x][y] = cap;
adj[x].push_back(y);
adj[y].push_back(x);
M--;
}
int maxFlow = MaxFlow(source, dest);
fout << maxFlow << endl;
}