Pagini recente » Cod sursa (job #2730659) | Cod sursa (job #1761078) | Cod sursa (job #1533125) | Cod sursa (job #2061850) | Cod sursa (job #2781461)
#include <bits/stdc++.h>
using namespace std;
template<typename T>
class MaxFlow{
private:
int n, m;
T f = 0;
vector<vector<int>> adj;
vector<vector<T>> capacity;
vector<vector<T>> dual;
vector<bool> visited;
vector<int> path;
public:
void Init(int n){
this->n = n;
adj = vector<vector<int>> (n + 1);
capacity = vector<vector<T>> (n + 1, vector<T>(n + 1));
dual = vector<vector<T>> (n + 1, vector<T>(n + 1));
visited = vector<bool> (n + 1, false);
}
void addEdge(int i, int j, T c){
m++;
adj[i].push_back(j);
adj[j].push_back(i);
capacity[i][j] = c;
dual[i][j] = c;
dual[j][i] = 0;
}
void DFS(int v, int t, vector<int>& path, bool& check){
if(check)
return;
visited[v] = true;
if(t == v){
check = true;
int l = path.size();
T M = dual[path[0]][path[1]];
for(int i = 0; i < l - 1; i++)
M = min(M, dual[path[i]][path[i + 1]]);
for(int i = 0; i < l - 1; i++){
dual[path[i]][path[i + 1]] -= M;
dual[path[i + 1]][path[i]] += M;
}
f += M;
return;
}
for(auto u : adj[v])
if(!visited[u] && dual[v][u] > 0){
path.push_back(u);
DFS(u, t, path, check);
path.pop_back();
}
}
T computeFlowDFS(int s, int t){
bool check = true;
while(check){
check = false;
path.clear();
path.push_back(s);
for(int i = 0; i <= n; i++)
visited[i] = false;
DFS(s, t, path, check);
}
return f;
}
};
int main() {
freopen("maxflow.in", "r", stdin);
freopen("maxflow.out", "w", stdout);
MaxFlow<int> f;
int n, m;
cin >> n >> m;
f.Init(n);
for(int i = 0; i < m; i++){
int a, b, c;
cin >> a >> b >> c;
f.addEdge(a, b, c);
}
cout << f.computeFlowDFS(1, n);
return 0;
}