Pagini recente » Cod sursa (job #2747207) | Cod sursa (job #2389420) | Cod sursa (job #567121) | Cod sursa (job #1614416) | Cod sursa (job #2962059)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <climits>
using namespace std;
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");
vector<vector<int>> graf, rgraf;
vector<int> parent;
int n, m, t, s;
void citire(){
int x, y, z;
fin>>n>>m;
s=1;
t=n;
graf.resize(n+1);
parent.resize(n+1);
rgraf.resize(n+1, vector<int>(n+1));
for(int i=0; i<m; i++){
fin >> x >> y >> z;
graf[x].push_back(y);
graf[y].push_back(x);
rgraf[x][y]= z;
}
}
bool bfs(){
vector<bool> vizitat(n+1,false);
queue<int> q;
q.push(s);
vizitat[s]= true;
parent[s]=-1;
while(!q.empty()){
int nod = q.front();
q.pop();
for(auto ad: graf[nod]) {
if (vizitat[ad] == false && rgraf[nod][ad] != 0) {
parent[ad] = nod; //tine minte drumul
if (ad == t)
return true;
vizitat[ad] = true;
q.push(ad);
}
}
}
return false; //nu am gasit drum
}
int fordf(){
int flowtotal= 0;
while(bfs()){
int u, v=t;
int pathflow= INT_MAX;
while(v != s){
//parcurgem invers
u = parent[v];
//aflam bottleneckul
if(rgraf[u][v] < pathflow)
pathflow= rgraf[u][v];
v = u;
}
v = t;
while( v!= s ){
u = parent[v];
rgraf[u][v] -= pathflow;
rgraf[v][u] += pathflow;
v = u;
}
flowtotal += pathflow;
}
return flowtotal;
}
int main()
{
citire();
fout << fordf();
return 0;
}