Pagini recente » Cod sursa (job #1877903) | Cod sursa (job #1870231) | Cod sursa (job #2195772) | Cod sursa (job #1870904) | Cod sursa (job #3317817)
#include <fstream>
#include <vector>
#include <queue>
#define NMAX 1002
#define INF (1<<30)
using namespace std;
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");
int N,M,tata[NMAX];
vector<int>graph[NMAX];
queue<pair<int,long long>>q;
long long cap[NMAX][NMAX];
void citire()
{
fin>>N>>M;
int x,y,z;
for(int i=1; i<=M;i++)
{
fin>>x>>y>>z;
graph[x].push_back(y);
graph[y].push_back(x);
cap[x][y]=z;
cap[y][x]=0;
}
}
long long BFS(int st, int dr)
{
while(!q.empty())
{
q.pop();
}
for(int i=1; i<=M; i++)
{
tata[i]=-1;
}
tata[st]=0;
q.push({st,INF});
while(!q.empty())
{
int nod=q.front().first;
long long flow=q.front().second;
q.pop();
for(int j=0; j<graph[nod].size(); j++)
{
int next_nod=graph[nod][j];
if(tata[next_nod]==-1 && cap[nod][next_nod]>0)
{
tata[next_nod]=nod;
long long new_flow=min(flow,cap[nod][next_nod]);
if(next_nod==dr)
{
return new_flow;
}
q.push({next_nod,new_flow});
}
}
}
return 0;
}
int main()
{
citire();
long long flow,new_flow;
flow=new_flow=0;
while(new_flow=BFS(1,N))
{
flow+=new_flow;
int nod=N;
while(nod!=1)
{
int prev_nod=tata[nod];
cap[prev_nod][nod]-=new_flow;
cap[nod][prev_nod]+=new_flow;
nod=prev_nod;
}
}
fout<< flow << "\n";
return 0;
}