Pagini recente » Cod sursa (job #623497) | Cod sursa (job #774687) | Cod sursa (job #2673548) | Cod sursa (job #866252) | Cod sursa (job #3335340)
//1.Algoritmul Ford-Fulkerson
#include <bits/stdc++.h>
#include <fstream>
#include <vector>
using namespace std;
const int MAXN = 1000;
int capac[MAXN+1][MAXN+1];
vector<int> adj[MAXN+1];
vector<int> parent;
vector<int> viz;
int n,m,x,y,c,flux_max, flux,s,t;
int bfs() {
fill(viz.begin(), viz.end(), 0);
queue<int> q;
q.push(s);
viz[s] = 1;
parent[s] = -1;
bool gasit =false;
while (q.size()>0 && gasit==false) {
int current = q.front();
q.pop();
for (auto vecin: adj[current]) {
if (viz[vecin] == 0 && capac[current][vecin] > 0) {
parent[vecin] = current;
viz[vecin] = 1;
if (vecin == t) {
gasit = true;
break;
}
q.push(vecin);
}
}
}
if (!viz[t]) return 0;
int flux_drum = INT_MAX;
int nod=t;
while (nod!=s) {
int parinte = parent[nod];
flux_drum = min(flux_drum,capac[parinte][nod]);
nod=parinte;
}
return flux_drum;
}
int main() {
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");
fin>>n>>m;
parent.assign(n+1,-1);
viz.assign(n+1,0);
s = 1; t = n;
for (int i = 0; i<m; i++) {
fin>>x>>y>>c;
adj[x].push_back(y);
adj[y].push_back(x);
capac[x][y] += c;
capac[y][x] += 0;
}
flux = bfs();
while (flux > 0) {
flux_max += flux;
int nod = t;
while (nod != s) {
int parinte = parent[nod];
capac[parinte][nod] -= flux;
capac[nod][parinte] += flux;
nod = parinte;
}
flux = bfs();
}
fout<<flux_max;
}