Pagini recente » Cod sursa (job #229356) | Cod sursa (job #841099) | Cod sursa (job #2644666) | Cod sursa (job #347144) | Cod sursa (job #3270927)
#include <fstream>
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
int n, m;
vector<vector<int>> graph;
vector<vector<int>> capacity;
int find_augmentated(int start, int end, vector<int>& parent)
{
fill(parent.begin(), parent.end(), -1);
queue<pair<int, int>> q;
q.emplace(start, 1e9);
while(!q.empty())
{
int node = q.front().first;
int flow = q.front().second;
q.pop();
for(int neigh: graph[node])
{
if(parent[neigh] == -1 && capacity[node][neigh] > 0)
{
int new_flow = min(flow, capacity[node][neigh]);
parent[neigh] = node;
if(neigh == end)
{
return new_flow;
}
q.emplace(neigh, new_flow);
}
}
}
return 0;
}
int maxflow(int start, int end)
{
int aug, flow = 0;
vector<int> parent(n + 1, -1);
while((aug = find_augmentated(start, end, parent)) != 0)
{
flow += aug;
int t = end;
while(t != start)
{
int prev = parent[t];
capacity[prev][t] -= aug;
capacity[t][prev] += aug;
t = prev;
}
}
return flow;
}
int main()
{
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");
fin >> n >> m;
graph.resize(n + 1);
capacity.resize(n + 1, vector<int>(n + 1, 0));
for (int i = 0; i < m; i++) {
int a, b, c;
fin >> a >> b >> c;
graph[a].push_back(b);
graph[b].push_back(a);
capacity[a][b] += c;
}
fout << maxflow(1, n);
return 0;
}