Pagini recente » Cod sursa (job #1108308) | Cod sursa (job #825602) | Cod sursa (job #480881) | Cod sursa (job #2618673) | Cod sursa (job #2959988)
#include <iostream>
#include <fstream>
#include <math.h>
#include <queue>
#define MAX 110000
/*
Idee de rezolvare: Algoritm Edmonds-Karp
Se face bfs pt a se gasi de fiecare data s-t lantul din graf cu lungime minima, se actualizeaza capacitatile si se revizuieste fluxul
de-a lungul lanturilor
Complexitate: O(n * m^2)
*/
using namespace std;
ifstream in("maxflow.in");
ofstream out("maxflow.out");
int n, m;
pair<int, int> muchie[1001][1001]; //fluxul si capacitatile pe muchii
vector<int> tata; //vectorul de tati
vector<int> l[1001]; //lista muchiilor
vector<int> cc; //capacitatea ramasa la mom. curent
int bfs(int s, int t)
{
queue <int> q;
//la fiecare parcurgere modificam vectorul de tati si capacitatile ramase
for(int i=0; i<=n; i++)
{
tata[i] = -1;
cc[i] = 0;
}
cc[s] = MAX; //capacitatea ramasa in sursa e maxima
q.push(s);
while(!q.empty())
{
int nod = q.front();
q.pop();
for(int i=0; i<l[nod].size(); i++)
{
int nodNou = l[nod][i];
if(tata[nodNou] == -1) //daca nodul curent nu a fost parcurs
{
//actualizez capaciatea curenta cu cea minima pe lant
if(muchie[nod][nodNou].second - muchie[nod][nodNou].first > 0)
{
tata[nodNou] = nod;
cc[nodNou] = min(cc[nod], muchie[nod][nodNou].second - muchie[nod][nodNou].first);
/*if(nodNou == t)
return cc[t];*/
q.push(nodNou);
}
}
}
}
return cc[t];
}
int fluxMax(int s, int t)
{
int rez = 0;
int flux = bfs(s, t);
while(flux != 0)
{
rez += flux;
int nod = t;
while(nod != s) //revizuiesc fluxul
{
int t = tata[nod];
muchie[t][nod].first += flux;
muchie[nod][t].first -= flux;
nod = t;
}
flux = bfs(s, t);
}
return rez;
}
int main()
{
in>>n>>m;
tata.resize(n+1);
cc.resize(n+1);
int x, y, z;
for(int i=1; i<=m; i++)
{
in>>x>>y>>z;
muchie[x][y].second = z;
muchie[x][y].first = 0;
l[x].push_back(y);
l[y].push_back(x);
}
out<<fluxMax(1, n);
return 0;
}