Pagini recente » Monitorul de evaluare | Cod sursa (job #984295)
Cod sursa(job #984295)
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
#define Nmax 1005
#define INF 0x3f3f3f3f
int *G[Nmax];
int tata[Nmax];
int viz[Nmax];
int C[Nmax][Nmax];
int F[Nmax][Nmax];
int coada[Nmax];
int degree[Nmax];
int N, M;
void read()
{
fstream f( "maxflow.in", ios::in );
f >> N >> M;
for ( int i = 1, a, b, c; i <= M; ++i )
{
f >> a >> b >> c;
degree[a]++;;
degree[b]++;
}
f.close();
f.open( "maxflow.in", ios::in );
f >> N >> M;
for ( int i = 1; i <= N; degree[i++] = 0 )
G[i] = new int[degree[i] + 1];
for ( int i = 1, a, b, c; i <= M; ++i )
{
f >> a >> b >> c;
C[a][b] += c;
G[a][ degree[a]++ ] = b;
G[b][ degree[b]++ ] = a;
}
for ( int i = 1; i <= N; i++ )
{
G[i][degree[i]] = -1;
degree[i] = 0;
}
f.close();
}
inline bool BFS( int sourse, int destination )
{
memset( viz, 0, sizeof( viz ) );
int st, fn;
coada[st = fn = 1] = 1;
viz[sourse] = 1;
for (; st <= fn; )
{
int nod = coada[ st++ ];
for ( int *v = G[nod]; *v != -1; v++ )
{
if ( !viz[ *v ] && !( F[nod][ *v ] >= C[nod][ *v ] ) ){
viz[ *v ] = 1;
tata[ *v ] = nod;
coada[ ++fn ] = *v;
if ( *v == destination )
return true;
}
}
}
return false;
}
int Edmonds_Karp( int sourse, int destination )
{
int flow, fmin, nod;
for ( flow = 0; BFS( sourse, destination ); )
{
for ( int *v = G[destination]; *v != -1; v++ )
{
if ( !viz[ *v ] || ( F[ *v ][destination] >= C[ *v ][destination] ) )
continue;
fmin = INF;
tata[destination] = *v;
for ( nod = destination; nod != sourse; nod = tata[nod] )
fmin = min( fmin, C[ tata[nod] ][nod] - F[ tata[nod] ][nod] );
if ( fmin == 0 )
continue;
for ( nod = destination; nod != sourse; nod = tata[nod] )
{
F[ tata[nod] ][nod] += fmin;
F[nod][ tata[nod] ] -= fmin;
}
flow += fmin;
}
}
return flow;
}
void print()
{
ofstream g("maxflow.out");
g << Edmonds_Karp( 1, N ) << "\n";
g.close();
}
int main()
{
read();
print();
return 0;
}