Pagini recente » Cod sursa (job #2661334) | Cod sursa (job #2691065) | Cod sursa (job #349205) | Cod sursa (job #1361198) | Cod sursa (job #2642715)
#include <bits/stdc++.h>
using namespace std;
const int NMAX = 355;
struct edge
{
int from , to , flow , cost;
};
int n , s ,t;
vector <int> adia[NMAX];
int cap[NMAX][NMAX] , p[NMAX] , d[NMAX] , cost[NMAX][NMAX],viz[NMAX];
bool bellman()
{
int i;
for(i = 1 ; i <= n; ++i)d[i]=1e9;
for(i=1;i<=n;++i)p[i]=-1;
memset(viz,0,sizeof(viz));
queue <int> q;
q.push(s);
d[s] = 0;
viz[s] = 1;
while(!q.empty())
{
int nod = q.front();
q.pop();
viz[nod] =0 ;
for(int i : adia[nod])
{
if(cap[nod][i] <= 0)continue;
if(d[i] > d[nod] + cost[nod][i])
{
d[i] = d[nod] + cost[nod][i];
if(!viz[i])
{
q.push(i);
viz[i]=1;
}
p[i] = nod;
}
}
}
return d[t]!=1e9;
}
int get_flow()
{
int t1 = t;
int f = 1e9;
for(;t1!=s;t1=p[t1])
f = min(f,cap[p[t1]][t1]);
return f;
}
int opt_flow(int flux)
{
int t1 = t;
for(;t1!=s;t1=p[t1])
{
cap[p[t1]][t1]-=flux;
cap[t1][p[t1]]+=flux;
}
return flux* d[t];
}
int min_cost_flow()
{
int cost = 0 ;
while(bellman())
cost += opt_flow(get_flow());
return cost;
}
int main()
{
freopen("fmcm.in","r",stdin);
freopen("fmcm.out","w",stdout);
int m,s1,d1;
cin>>n>>m>>s>>t;
for(int i=1;i<=m;i++)
{
int a,b,c,d;
cin>>a>>b>>c>>d;
cap[a][b] = c;
cap[b][a] = 0;
cost[a][b] = d;
cost[b][a] = -d;
adia[a].push_back(b);
adia[b].push_back(a);
}
int res=min_cost_flow();
cout<<res;
return 0;
}