Pagini recente » Cod sursa (job #481141) | Cod sursa (job #2759091) | Cod sursa (job #1844303) | Cod sursa (job #1766168) | Cod sursa (job #1486337)
#include <iostream>
#include <cstdio>
#include <vector>
#include <queue>
using namespace std;
const int MAXN = 1000, INF = 2000000000;
int cap[MAXN+1][MAXN+1], numNodes, numEdges, father[MAXN+1], answer;
vector <int> G[MAXN+1];
bool viz[MAXN+1];
void readData()
{
scanf("%d %d",&numNodes,&numEdges);
for(int i = 1; i <= numEdges; i++)
{
int nodeX, nodeY, capXY;
scanf("%d %d %d",&nodeX,&nodeY,&capXY);
G[ nodeX ].push_back( nodeY );
G[ nodeY ].push_back( nodeX );
cap[ nodeX ][ nodeY ] += capXY;
}
}
int findFlowIncrease()
{
int node = numNodes, flowIncrease = INF;
while( node != 1 )
{
int prevNode = father[ node ];
flowIncrease = min( flowIncrease, cap[ prevNode ][ node ] );
node = prevNode;
}
answer += flowIncrease;
return flowIncrease;
}
void updateFlow()
{
int node = numNodes, flowIncrease = findFlowIncrease();
while( node != 1 )
{
int prevNode = father[ node ];
cap[ prevNode ][ node ] -= flowIncrease;
cap[ node ][ prevNode ] += flowIncrease;
node = prevNode;
}
}
void zeroVizAndFather()
{
for(int i = 1; i <= numNodes; i++)
{
viz[ i ] = false;
father[ i ] = 0;
}
}
bool findAugPaths()
{
queue <int> c;
zeroVizAndFather();
c.push( 1 );
while( c.empty() == false )
{
int currNode = c.front();
if( currNode == numNodes )
return true;
viz[ currNode ] = true;
for(int i = 0; i < G[ currNode ].size(); i++)
{
int nextNode = G[ currNode ][ i ];
if( viz[ nextNode ] == false && cap[ currNode ][ nextNode ] > 0 )
{
c.push( nextNode );
father[ nextNode ] = currNode;
}
}
c.pop();
}
return false;
}
void findMaxFlow()
{
while( findAugPaths() == true )
{
for(int i = 0; i < G[ numNodes ].size(); i++)
{
int currNode = G[ numNodes ][ i ];
if( father[ currNode ] != 0 )
{
father[ numNodes ] = currNode;
updateFlow();
}
}
}
}
int main()
{
freopen("maxflow.in","r",stdin);
freopen("maxflow.out","w",stdout);
readData();
findMaxFlow();
printf("%d",answer);
return 0;
}