Pagini recente » Istoria paginii utilizator/mihaitica | Cod sursa (job #988804)
Cod sursa(job #988804)
#include <fstream>
#include <queue>
#include <cstring>
#include <vector>
using namespace std;
const int Nmax = 1010;
const int Mmax = 5010;
ifstream F("maxflow.in");
ofstream G("maxflow.out");
#define IT(type) vector<type>::iterator
int N,M,total_flow;
vector<int> V[Nmax];
vector<int> neighbours;
int capacity[Nmax][Nmax];
int last[Nmax],Cmin[Nmax];
int find_paths(int source,int target)
{
queue<int> Q;
memset(last,0,sizeof(last));
last[source] = -1;
Q.push( source );
while ( Q.size() )
{
int node = Q.front();
Q.pop();
for (IT(int) where=V[node].begin();where!=V[node].end();++where)
if ( capacity[node][*where] > 0 && last[*where] == 0 )
{
last[*where] = node;
Q.push( *where );
}
}
neighbours.clear();
for (IT(int) node=V[target].begin();node!=V[target].end();++node)
if ( last[ *node ] != 0 && capacity[*node][target] > 0 )
neighbours.push_back( *node );
if ( last[target] == 0 )
return 0;
return 1;
}
int main()
{
F>>N>>M;
for (int i=1,x,y,c;i<=M;++i)
{
F>>x>>y>>c;
if ( capacity[x][y] == 0 && capacity[y][x] == 0 )
{
V[ x ].push_back( y );
V[ y ].push_back( x );
}
capacity[x][y] += c;
}
int source = 1;
int target = N;
while ( find_paths(source,target) != 0 )
{
int debug = 1;
for (IT(int) neighbour=neighbours.begin();neighbour!=neighbours.end();++neighbour)
{
Cmin[*neighbour] = capacity[*neighbour][target];
for (int now=*neighbour;now!=source;now=last[now])
Cmin[*neighbour] = min( Cmin[*neighbour] , capacity[last[now]][now] );
total_flow += Cmin[*neighbour];
for (int now=*neighbour;now!=source;now=last[now])
{
capacity[last[now]][now] -= Cmin[*neighbour];
capacity[now][last[now]] += Cmin[*neighbour];
}
capacity[*neighbour][target] -= Cmin[*neighbour];
}
}
G<<total_flow<<'\n';
}