Pagini recente » Cod sursa (job #866901) | Cod sursa (job #1428957) | Cod sursa (job #1443468) | Cod sursa (job #2176527) | Cod sursa (job #984139)
Cod sursa(job #984139)
#include <iostream>
#include <fstream>
#include <vector>
#include <bitset>
#include <queue>
#include <cstring>
using namespace std;
#define Nmax 1005
#define Mmax 5005
#define INF 0x3f3f3f3f3f
vector <int> G[Nmax];
vector <int> tata(Nmax);
int viz[Nmax];
queue <int> Q;
int C[Nmax][Nmax], F[Nmax][Nmax];
int N, M;
void read()
{
ifstream f("maxflow.in");
f >> N >> M;
for ( int i = 1, a, b, c; i <= M; ++i )
{
f >> a >> b >> c;
C[a][b] = c;
G[a].push_back( b );
}
f.close();
}
int BFS( int sourse, int destination )
{
int i, j, nod, V;
memset(viz, 0, sizeof(viz));
viz[1] = 1;
Q.push( 1 );
for ( ; !Q.empty(); )
{
nod = Q.front();
Q.pop();
for ( unsigned j = 0; j < G[nod].size(); j++)
{
V = G[nod][j];
if (C[nod][V] == F[nod][V] || viz[V]) continue;
viz[V] = 1;
Q.push( V );
tata[V] = nod;
if (V == N) return 1;
}
}
return 0;
}
int Ford_Fulkerson( int sourse, int destination )
{
int max_flow, fmin, nod;
for ( max_flow = 0; BFS( sourse, destination ); max_flow += fmin )
{
fmin = INF;
for ( nod = destination; nod != sourse; nod = tata[nod] )
fmin = min( fmin, C[ tata[nod] ][nod] - F[ tata[nod] ][nod] );
for ( nod = destination; nod != sourse; nod = tata[nod] )
{
F[ tata[nod] ][nod] += fmin;
F[nod][ tata[nod] ] -= fmin;
}
}
return max_flow;
}
void print()
{
ofstream g("maxflow.out");
g << Ford_Fulkerson( 1, N ) << "\n";
g.close();
}
int main()
{
read();
print();
return 0;
}