Pagini recente » Cod sursa (job #803882) | Cod sursa (job #803867) | Cod sursa (job #3357534) | Cod sursa (job #3357533) | Cod sursa (job #3358026)
#include <fstream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
const int NMAX = 1005;
const int INF = 1e9;
int n, m;
int cap[NMAX][NMAX];
vector<int> adj[NMAX];
int bfs(int s, int t, vector<int>& parent) {
fill(parent.begin(), parent.end(), -1);
parent[s] = s;
queue<pair<int, int>> q;
q.push({s, INF});
while (!q.empty()) {
int u = q.front().first;
int flow = q.front().second;
q.pop();
for (int v : adj[u]) {
if (parent[v] == -1 && cap[u][v] > 0) {
parent[v] = u;
int new_flow = min(flow, cap[u][v]);
if (v == t) return new_flow;
q.push({v, new_flow});
}
}
}
return 0;
}
int maxflow(int s, int t) {
int flow = 0;
vector<int> parent(n + 1);
int new_flow;
while ((new_flow = bfs(s, t, parent))) {
flow += new_flow;
int cur = t;
while (cur != s) {
int prev = parent[cur];
cap[prev][cur] -= new_flow;
cap[cur][prev] += new_flow;
cur = prev;
}
}
return flow;
}
int main() {
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");
fin >> n >> m;
for (int i = 0; i < m; i++) {
int x, y, z;
fin >> x >> y >> z;
cap[x][y] += z;
adj[x].push_back(y);
adj[y].push_back(x);
}
fout << maxflow(1, n);
fin.close();
fout.close();
return 0;
}