Pagini recente » Cod sursa (job #2747817) | Cod sursa (job #646438) | Cod sursa (job #167132) | Cod sursa (job #2194122) | Cod sursa (job #2900278)
#include <bits/stdc++.h>
using namespace std;
#ifdef LOCAL
ifstream in("in.in");
ofstream out("out.out");
#else
ifstream in("maxflow.in");
ofstream out("maxflow.out");
#endif
const int nmax = 1005;
int n,m,cap[nmax][nmax],flow[nmax][nmax];
vector<int> dis,viz;
vector<vector<int>> g;
const int inf = 1000000005;
bool get_level_graph() {
queue<int> q;
dis = vector<int>(n + 1, inf);
viz = vector<int>(n + 1, 0);
dis[1] = 0;
q.push(1);
while(!q.empty()) {
int node = q.front();
q.pop();
for (auto k : g[node]) {
if (dis[k] > dis[node] + 1 && cap[node][k] > flow[node][k]) {
dis[k] = dis[node] + 1;
q.push(k);
}
}
}
return dis[n] < inf;
}
inline bool isOkay(int from , int to) {
return dis[from] < dis[to] && flow[from][to] < cap[from][to];
}
int find_augmenting_path() {
vector<int> path;
function<bool(int)> dfs = [&](int node) {
if (node == n) {
path.push_back(node);
return true;
}
viz[node] = 1;
for (auto k : g[node]) {
if (viz[k] == 0 && isOkay(node, k)) {
if (dfs(k)) {
path.push_back(node);
return true;
} else {
dis[k] = -1;
}
}
}
viz[node] = 0;
return false;
};
if (dfs(1) == false) {
return 0;
}
reverse(path.begin() , path.end());
int bottle_neck = inf;
for (int i = 0; i + 1 < path.size(); i++) {
bottle_neck = min(bottle_neck ,cap[path[i]][path[i + 1]] - flow[path[i]][path[i + 1]]);
}
for (int i = 0; i + 1 < path.size(); i++) {
flow[path[i]][path[i + 1]] += bottle_neck;
flow[path[i + 1]][path[i]] -= bottle_neck;
}
return bottle_neck;
}
int maxflow() {
int total_flow = 0;
while(get_level_graph()) {
while(true) {
int added_flow = find_augmenting_path();
if (added_flow == 0) {
break;
} else {
total_flow += added_flow;
}
}
}
return total_flow;
}
int main() {
in >> n >> m;
g.resize(n + 1);
for (int i = 1; i <= m; i++) {
int u,v,c;
in >> u >> v >> c;
g[u].push_back(v);
g[v].push_back(u);
cap[u][v] += c;
}
out << maxflow() << "\n";
}