Pagini recente » Cod sursa (job #848113) | Cod sursa (job #792867) | Cod sursa (job #2371487) | Cod sursa (job #2038644) | Cod sursa (job #985026)
Cod sursa(job #985026)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <cstring>
#include <climits>
using namespace std;
#define Nmax 1002
vector <int> G[Nmax];
queue <int> Q;
int F[Nmax][Nmax];
int C[Nmax][Nmax];
int visit[Nmax];
int level[Nmax];
inline bool ConstructLevelGraph( int source, int sink )
{
fill( level, level + Nmax, -1 );
level[source] = 0;
Q.push( source );
while( !Q.empty() )
{
int nod = Q.front();
Q.pop();
for ( unsigned i = 0; i < G[nod].size(); ++i )
{
int son = G[nod][i];
if ( level[son] == -1 && F[nod][son] < C[nod][son] )
{
level[son] = level[nod] + 1;
Q.push( son );
}
}
}
return ( level[sink] >= 0 );
}
inline int ConstructBlockingFlow( int source, int sink, int dest )
{
if ( source == dest )
return sink;
visit[source] = 1;
for ( unsigned i = 0; i < G[source].size(); ++i )
{
int son = G[source][i];
if ( !visit[son] && C[source][son] > F[source][son] )
{
if ( level[son] == level[source] + 1 )
{
int df = ConstructBlockingFlow( son, min( sink, C[source][son] - F[source][son]), dest );
if ( df )
{
F[source][son] += df;
F[son][source] -= df;
return df;
}
}
}
}
return 0;
}
int Dinic( int source, int sink )
{
int flow = 0;
while( ConstructLevelGraph( source, sink ) )
{
fill( visit, visit + Nmax, 0 );
while( int flw = ConstructBlockingFlow( source, INT_MAX, sink ) )
flow += flw;
}
return flow;
}
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 );
G[b].push_back( a );
}
f.close();
}
void print()
{
ofstream g("maxflow.out");
g << Dinic( 1, N ) << "\n";
g.close();
}
int main()
{
read();
print();
return 0;
}