Pagini recente » Cod sursa (job #1152999) | Cod sursa (job #158515) | Cod sursa (job #102227) | Cod sursa (job #1400870) | Cod sursa (job #3202944)
#include <bits/stdc++.h>
#define N 1004
#define inf 2e9
using namespace std;
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");
int n, m;
int sursa;
struct muchie{
int f, c;
} M[N][N];
vector<int> g[N], h[N];
void Citire()
{
int i;
int x, y, c;
fin >> n >> m;
sursa = 1;
for( i=1; i<=m; i++ ){
fin >> x >> y >> c;
g[x].push_back(y); M[x][y] = {0, c};
h[y].push_back(x); M[y][x] = {0, c};
}
}
queue<int> Q;
int Dad[N];
bool viz[N];
bool BFS()
{
int i;
for( i=1; i<=n; i++ )
Dad[i] = inf, viz[i] = 0;
while(!Q.empty()) Q.pop();
Q.push(sursa);
viz[sursa] = 1;
while( !Q.empty() )
{
int nod = Q.front();
Q.pop();
for( auto next : g[nod] ) /// arc direct
if( viz[next] == 0 && M[nod][next].c > M[nod][next].f ){
Q.push(next);
viz[next] = 1;
Dad[next] = nod;
if( next == n ) return true;
}
for( auto next : h[nod] ) /// arc invers
if( viz[next] == 0 && M[nod][next].f > 0 ){
Q.push(next);
viz[next] = 1;
Dad[next] = -nod;
if( next == n ) return true;
}
}
return 0;
}
void Revizuire( int x, int &mn )
{
if( x == sursa ) return;
if( Dad[x] >= 0 ){
mn = min(mn, M[Dad[x]][x].c - M[Dad[x]][x].f);
Revizuire( Dad[x], mn );
M[Dad[x]][x].f += mn;
M[x][Dad[x]].f += mn;
}
if( Dad[x] < 0 ){
mn = min(mn, M[-Dad[x]][x].f);
Revizuire( -Dad[x], mn );
M[-Dad[x]][x].f -= mn;
M[x][-Dad[x]].f -= mn;
}
}
void Rezolvare()
{
while( BFS() ){
int mn = inf;
Revizuire(n, mn);
}
int flux = 0;
for( auto nod : g[sursa] ) flux += M[sursa][nod].f;
fout << flux;
}
int main()
{
Citire();
Rezolvare();
return 0;
}