Pagini recente » Cod sursa (job #1910061) | Cod sursa (job #2307533) | Cod sursa (job #1118617) | Cod sursa (job #2412424) | Cod sursa (job #2749078)
#include <bits/stdc++.h>
#define pb push_back
#include <fstream>
using namespace std;
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");
const int MAXN = 1e4;
vector<int> graph[MAXN];
int cap[MAXN][MAXN], fl[MAXN][MAXN], par[MAXN];
void dfs(int node, int parent, int dest, bool &found) {
par[node] = parent;
if (node == dest) {
found = true;
return;
}
for (const auto& it: graph[node])
if (par[it] == -1 && cap[node][it] > fl[node][it]) {
dfs(it, node, dest, found);
if (found)
return;
}
}
bool isPath(int source, int dest) {
bool found = false;
memset(par, -1, sizeof(par));
dfs(source, source, dest, found);
return par[dest] != -1;
}
int getMinFlow(int dest) {
int node = dest, flow = INT_MAX;
while (node != par[node]) {
flow = min(flow, cap[par[node]][node] - fl[par[node]][node]);
node = par[node];
}
return flow;
}
void updatePath(int dest, int flow) {
int node = dest;
while (node != par[node]) {
fl[par[node]][node] += flow;
node = par[node];
}
}
int getFlow(int source, int dest) {
int maxFlow = 0;
memset(fl, 0, sizeof(fl));
while (isPath(source, dest)) {
int flow = getMinFlow(dest);
maxFlow += flow;
updatePath(dest, flow);
}
return maxFlow;
}
void read(int& source, int& dest) {
int n, m;
fin >> n >> m;
source = 1;
dest = n;
for (int i = 0; i < m; ++i) {
int x, y, c;
fin >> x >> y >> c;
graph[x].pb(y);
graph[y].pb(x);
cap[x][y] = cap[y][x] = c;
}
}
int main() {
int source, dest;
read(source, dest);
fout << getFlow(source, dest);
return 0;
}