Pagini recente » Cod sursa (job #3217254) | Cod sursa (job #2265690) | Cod sursa (job #1456726) | Cod sursa (job #2841634) | Cod sursa (job #2411415)
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream in("maxflow.in");
ofstream out("maxflow.out");
const int N=1005;
const int INF=(1<<30);
vector<int>a[N];
int n,m,c[N][N],flow[N][N],pred[N],maxflow;
bool viz[N];
bool bfs()
{
for(int i=1;i<=n;i++)
viz[i]=false;
queue<int>q;
q.push(1);
viz[1]=true;
int x,y;
while(!q.empty())
{
x=q.front();
q.pop();
for(unsigned i=0;i<a[x].size();i++)
{
y=a[x][i];
if(!viz[y] && c[x][y]>flow[x][y])
{
viz[y]=true;
pred[y]=x;
q.push(y);
if(y==n)
return true;
}
}
}
return false;
}
int main()
{
int x,y,capacity;
in>>n>>m;
for(int i=1;i<=m;i++)
{
in>>x>>y>>capacity;
a[x].push_back(y);
a[y].push_back(x);
c[x][y]=capacity;
}
int bottleneck;
while(bfs())
for(unsigned i=0;i<a[n].size();i++)
{
y=a[n][i];
if(viz[y]==true)
{
pred[n]=y;
bottleneck=INF;
x=n;
while(x!=1)
{
bottleneck=min(bottleneck,c[pred[x]][x]-flow[pred[x]][x]);
x=pred[x];
}
maxflow=maxflow+bottleneck;
x=n;
while(x!=1)
{
flow[pred[x]][x]=flow[pred[x]][x]+bottleneck;
flow[x][pred[x]]=flow[x][pred[x]]-bottleneck;
x=pred[x];
}
}
}
out<<maxflow;
return 0;
}