Pagini recente » Cod sursa (job #1625086) | Cod sursa (job #2504268) | Cod sursa (job #1436434) | Cod sursa (job #1418540) | Cod sursa (job #1688340)
#include <bits/stdc++.h>
#define mp make_pair
#define pb push_back
#define INF numeric_limits<int>::max()
#define int64 long long
using namespace std;
ifstream in("fmcm.in");
ofstream out("fmcm.out");
vector< vector<int> > adj;
int n,m,cost[1024][1024],flow[1024][1024],cap[1024][1024],pre[1024],S,D,dist[1024];
bool use[1024];
queue<int> Q;
bool bellman()
{
for(int i=1;i<=n;i++)
{
dist[i]=INF;
pre[i]=0;
use[i]=false;
}
Q.push(S);
dist[S]=0;
pre[S]=S;
while(!Q.empty())
{
int x=Q.front();
Q.pop();
use[x]=false;
for(auto it: adj[x])
if(dist[it] > dist[x] + cost[x][it] && cap[x][it]>flow[x][it])
{
dist[it]=dist[x] + cost[x][it];
pre[it]=x;
if(use[it]==false)
{
use[it]=true;
Q.push(it);
}
}
}
return (pre[D]!=0);
}
int main()
{
in>>n>>m>>S>>D;
adj=vector< vector<int> > (n+1);
for(;m;m--)
{
int x,y,z,w;
in>>x>>y>>z>>w;
adj[x].pb(y);
adj[y].pb(x);
cap[x][y]=z;
cost[x][y]=w;
cost[y][x]=-w;
}
int maxflow=0,totalCost=0;
while(bellman()==true)
{
int mx=INF;
for(int x=D;x!=pre[x];x=pre[x])
mx=min(mx,cap[pre[x]][x]-flow[pre[x]][x]);
for(int x=D;x!=pre[x];x=pre[x])
{
flow[pre[x]][x]+=mx;
flow[x][pre[x]]-=mx;
totalCost+=cost[pre[x]][x]*mx;
}
maxflow+=mx;
}
out<<totalCost<<'\n';
return 0;
}