Pagini recente » Cod sursa (job #3334221) | Monitorul de evaluare | Cod sursa (job #3343839) | Cod sursa (job #3310900) | Cod sursa (job #3327357)
#include <bits/stdc++.h>
using namespace std;
ifstream f("maxflow.in");
ofstream g("maxflow.out");
int n, m, x, y, c, dist[1005], cap[1005][1005], flow[1005][1005];
int ans = 0;
vector <int> v[1005];
// intr-un bfs, gasesc toate drumurile augumentate cele mai scurte ca distanta
// deci verifica daca o sa mai pot ajunge la destinatie printr-un drum augumentat
bool bfs (int source, int destination) {
for (int i=1; i<=n; ++i)
dist[i] = INT_MAX;
dist[source] = 0;
queue <int> q;
q.push (source);
while (!q.empty()) {
int k = q.front();
q.pop();
for (auto x: v[k])
if (cap[k][x] > flow[k][x] && dist[x] > dist[k] + 1) {
dist[x] = dist[k] + 1;
q.push (x);
}
}
return dist[destination] != INT_MAX;
}
int maxFlow (int node, int destination, int max_flow) {
if (max_flow == 0)
return 0;
if (node == destination)
return max_flow;
int total_flow = 0;
for (auto x: v[node])
if (dist[x] == dist[node] + 1) {
int new_max_flow = min (max_flow - total_flow, cap[node][x] - flow[node][x]);
int new_flow = maxFlow (x, destination, new_max_flow);
flow[node][x] += new_flow;
flow[x][node] -= new_flow;
total_flow += new_flow;
}
return total_flow;
}
void Flow () {
while (bfs (1, n))
ans += maxFlow (1, n, INT_MAX);
}
int main()
{
f >> n >> m;
for (int i=1; i<=m; ++i) {
f >> x >> y >> c;
v[x].push_back (y);
v[y].push_back (x);
cap[x][y] = c;
}
Flow();
g << ans;
return 0;
}