Pagini recente » Cod sursa (job #3265606) | Cod sursa (job #303104) | Cod sursa (job #3287103) | Cod sursa (job #234303) | Cod sursa (job #2961116)
#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 <int> adj[1005];
int capacity[1005][1005], parent[1005];
bool vis[1005];
int BFS(int start, int end)
{
memset(parent, 0, N + 5);
memset(vis, false, N + 5);
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;
for (auto& line : adj)
line.resize(N + 5, 0);
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;
}