Pagini recente » Cod sursa (job #1982827) | Cod sursa (job #1228476) | Cod sursa (job #2035506) | Cod sursa (job #2544401) | Cod sursa (job #984137)
Cod sursa(job #984137)
#include <iostream>
#include <fstream>
#include <vector>
#include <bitset>
#include <queue>
using namespace std;
#define Nmax 1005
#define Mmax 5005
#define INF 0x3f3f3f3f3f
vector <int> G[Nmax];
vector <int> tata(Nmax);
bitset <Nmax> viz;
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();
}
inline bool BFS( int sourse, int destination )
{
for ( int i = sourse; i <= destination; ++i )
viz[i] = 0;
Q.push( sourse );
viz[sourse] = 1;
while( !Q.empty() )
{
int nod = Q.front();
Q.pop();
for ( unsigned i = 0; i < G[nod].size(); ++i )
if ( !viz[ G[nod][i] ] && C[nod][ G[nod][i] ] > F[nod][ G[nod][i] ] )
{
Q.push( G[nod][i] );
tata[ G[nod][i] ] = nod;
viz[ G[nod][i] ] = true;
if ( G[nod][i] == destination )
return true;
}
}
return false;
}
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;
}