Pagini recente » Cod sursa (job #3240592) | Cod sursa (job #3184697) | Cod sursa (job #1931699) | Cod sursa (job #119120) | Cod sursa (job #2961671)
#include <bits/stdc++.h>
#define oo 1e9
using namespace std;
class Algo{
private:
vector<vector<int> > cap;
vector<vector<vector<int> > > muchie;
vector<int> nivel;
int n, t;
int max_flow;
bool BFSMF(int act){
bool ok = false;
queue<pair<int, int> > q;
q.push({act,0});
vector<bool> viz(n, false);
viz[act] = true;
nivel[act] = 0;
while(!q.empty()){
int nct = q.front().first;
int nv = q.front().second;
if(nct == t) ok = true;
q.pop();
for(auto j:muchie[nct]){
if(nivel[j[0]] == -1 && j[1]){
q.push({j[0],nv+1});
nivel[j[0]] = nv + 1;
}
}
}
return ok;
}
int DFSMF(int act, int cost){
if(act == t) return cost;
int ctactm = -1;
for(auto j:muchie[act]){
ctactm++;
if(j[2] == 0 && j[1] != 0 && (nivel[j[0]] - nivel[act] == 1) && !j[2]) {
int ct = min(cost, j[1]);
ct = DFSMF(j[0], ct);
if (ct == -1) j[2] = 1;
else {
muchie[act][ctactm][1] -= ct;
muchie[j[0]].push_back({act, ct, 0});
return ct;
}
}
}
return -1;
}
public:
int MaxFlow(vector<vector<int> > &capi, int ni, int s, int ti){
t = ti;
this->cap = capi;
n = ni;
muchie.clear();
muchie.assign(n, {});
for(auto j:cap){
muchie[j[0]].push_back({j[1], j[2], 0});
}
max_flow = 0;
while(true){
nivel.clear();
nivel.assign(n, -1);
if(!BFSMF(s)) return max_flow;
int flow = 0;
do{
flow = DFSMF(s, oo);
if(flow != -1)
max_flow += flow;
}while(flow != -1);
}
}
};
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");
int main() {
int n, m;
fin >> n >> m;
vector<vector<int>> cap;
for(int i = 0; i < m; i++){
int x, y, c;
fin >> x >> y >> c;
cap.push_back({x - 1, y - 1, c});
}
Algo a;
fout<<a.MaxFlow(cap, n, 0, n-1);
return 0;
}