Pagini recente » Cod sursa (job #295870) | Cod sursa (job #2247515) | Cod sursa (job #199078) | Cod sursa (job #1475154) | Cod sursa (job #2954818)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <fstream>
using namespace std;
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");
#define N 1001
int n, m, maxFlow;
int s, t;
int capacity[N][N];
vector<vector<int>> l(N, vector<int>());
vector<int> parent(N);
int bfs(int s, int t) {
parent[s] = -2; // ?
queue<pair<int, int>> q;
q.push({ s, 1e9 });
while (!q.empty()) {
int cur = q.front().first;
int maxFlow = q.front().second;
q.pop();
for (int next : l[cur]) {
if (parent[next] == -1 && capacity[cur][next]) {
parent[next] = cur;
int bottleneck = min(maxFlow, capacity[cur][next]);
if (next == t)
return bottleneck;
q.push({ next, bottleneck });
}
}
}
return 0;
}
void read() {
fin >> n >> m;
while (m--) {
int a, b, c;
fin >> a >> b >> c;
l[a].push_back( b );
l[b].push_back( a );
capacity[a][b] += c; // muchia de inaintare
capacity[b][a] = 0; // muchia de intoarcere (intial nu se poate face undo deoarece nu trece nimic)
}
}
int main() {
read();
s = 1; t = n;
for (int i = 1; i <= n; i++) // resetam parintii
parent[i] = -1;
int bottleneck;
while (bottleneck = bfs(s, t)) { // cat mai sunt path uri care mai accepta flux
maxFlow += bottleneck;
int cur = t;
while (cur != s) { // mergem inapoi pe path ul gasit
int prev = parent[cur];
capacity[prev][cur] -= bottleneck; // muchia de inaintare
capacity[cur][prev] += bottleneck;
cur = prev;
}
for (int i = 1; i <= n; i++) // resetam parintii
parent[i] = -1;
}
fout << maxFlow;
return 0;
}