Pagini recente » Cod sursa (job #1546305) | Cod sursa (job #1859456) | Cod sursa (job #215175) | Cod sursa (job #721068) | Cod sursa (job #2679146)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#define NMAX 1005
using namespace std;
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");
struct edge {
int u, capacity, flow = 0, r;
};
struct p {
int u, i;
};
vector<edge> g[NMAX];
p parent[NMAX];
int n;
bool bfs(int u) {
bool viz[NMAX] = { 0 };
queue<int> q;
q.push(u);
parent[u] = { 0,-1 };
viz[u] = true;
while (!q.empty()) {
u = q.front();
q.pop();
if (u == n) return true;
for (int i = 0;i < g[u].size();++i) {
const auto& v = g[u][i];
if (viz[v.u] == false && v.flow < v.capacity) {
viz[v.u] = true;
parent[v.u] = { u,i };
q.push(v.u);
}
}
}
return false;
}
int max_flow() {
int flow = 0;
while (bfs(1)) {
int min_flow = 1e9;
int u = n;
while (parent[u].u != 0) {
const auto& v = parent[u];
const auto& e = g[v.u][v.i];
if (e.capacity - e.flow < min_flow)
min_flow = e.capacity - e.flow;
u = v.u;
}
u = n;
while (parent[u].u != 0) {
const auto& v = parent[u];
auto& e = g[v.u][v.i];
e.flow += min_flow;
g[e.u][e.r].flow -= min_flow;
u = v.u;
}
flow += min_flow;
}
return flow;
}
void read() {
int m;
fin >> n >> m;
while (m--) {
int u, v, c;
fin >> u >> v >> c;
g[u].push_back({ v,c,0,(int)g[v].size() });
g[v].push_back({ u,0,0,(int)g[u].size() - 1 });
}
}
int main() {
read();
fout << max_flow();
return 0;
}