Pagini recente » Cod sursa (job #1433489) | Cod sursa (job #1663620) | Cod sursa (job #1182091) | Cod sursa (job #1998712) | Cod sursa (job #2814813)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <stack>
#include <algorithm>
#include <climits>
#define MAX 101
using namespace std;
ifstream inmaxflow("maxflow.in");
ofstream outmaxflow("maxflow.out");
class Graf
{
int NrNoduri;
public:
vector<int> Adiacenta[MAX];
Graf(int NrNoduri);
bool bfs(int rGraf[MAX][MAX], int sursa, int destinatie, int parinte[]);
int MaxFlow(int Graf[MAX][MAX], int sursa, int destinatie);
};
Graf::Graf(int NrNoduri)
{
this->NrNoduri = NrNoduri;
}
bool Graf :: bfs(int rGraf[MAX][MAX], int sursa, int destinatie, int parinte[])
{
bool Vizitat[MAX] = {0};
queue<int> Q;
Q.push(sursa);
Vizitat[sursa] = 1;
parinte[sursa] = -1;
while(!Q.empty())
{
int nodcurent = Q.front();
Q.pop();
for (int nod = 1; nod <= NrNoduri; nod++)
{
if (!Vizitat[nod] && rGraf[nodcurent][nod] > 0)
{
Q.push(nod);
parinte[nod] = nodcurent;
Vizitat[nod] = 1;
if (nod == destinatie)
return 1;
}
}
}
return 0;
}
int Graf :: MaxFlow(int Graf[MAX][MAX], int sursa, int destinatie)
{
int rGraf[MAX][MAX];
for (int i = 1; i <= NrNoduri; i++)
for (int j = 1; j <= NrNoduri; j++)
rGraf[i][j] = Graf[i][j];
int totalFlow = 0;
int parinte[MAX];
while (bfs(rGraf, sursa, destinatie, parinte))
{
int drumFlow = INT_MAX;
int j = destinatie;
while (j != sursa)
{
int i = parinte[j];
drumFlow = min(drumFlow, rGraf[i][j]);
j = parinte[j];
}
j = destinatie;
while (j != sursa)
{
int i = parinte[j];
rGraf[i][j] -= drumFlow;
rGraf[j][i] += drumFlow;
j = parinte[j];
}
totalFlow += drumFlow;
}
return totalFlow;
}
int main()
{
int N , M;
inmaxflow >> N >> M;
Graf g(N);
int G[MAX][MAX] = {0};
int nod1, nod2, capacitate;
for(int i = 0 ; i < M; i++)
{
inmaxflow >> nod1 >> nod2 >> capacitate;
G[nod1][nod2] = capacitate;
}
outmaxflow << g.MaxFlow(G, 1, N);
return 0;
}