Pagini recente » Cod sursa (job #175441) | Cod sursa (job #2802896) | Cod sursa (job #249272) | Cod sursa (job #775514) | Cod sursa (job #2909254)
#include <bits/stdc++.h>
#define N 400
#define INF 0x3f3f3f3f
using namespace std;
ifstream fin("fmcm.in");
ofstream fout("fmcm.out");
struct muchie
{
int x,y,c,z;
};
vector<int>g[N];
int capacity[N][N],cost[N][N];
bool viz[N];
int n,m,s,t,maxFlow;
long long minCost;
int d[N],dp[N],D[N],tata[N];
queue<int>q;
void BellmanFord()
{
d[s]=0;
q.push(s);
viz[s]=1;
while(!q.empty())
{
int nod=q.front();
q.pop();
viz[nod]=0;
for(auto x:g[nod])
if(capacity[nod][x] && d[x]>d[nod]+cost[nod][x])
{
d[x]=d[nod]+cost[nod][x];
if(!viz[x]) viz[x]=1,q.push(x);
}
}
}
struct myqueue
{
int nod,cost;
bool operator < (const myqueue x) const
{
return x.cost<cost;
}
};
priority_queue<myqueue>pq;
bool Dijkstra()
{
memset(dp,INF,sizeof(dp));
dp[s]=D[s]=0;
pq.push({s,0});
while(!pq.empty())
{
int nod=pq.top().nod;
int z=pq.top().cost;
pq.pop();
if(z!=dp[nod]) continue;
for(auto x:g[nod])
{
if(!capacity[nod][x]) continue;
int newCost=z+cost[nod][x]+d[nod]-d[x];
if(newCost<dp[x])
{
dp[x]=newCost;
D[x]=D[nod]+cost[nod][x];
tata[x]=nod;
if(x!=t) pq.push({x,newCost});
}
}
}
if(dp[t]==INF) return 0;
int minFlow=INF;
for(int x=t;x!=s;x=tata[x])
{
minFlow=min(minFlow,capacity[tata[x]][x]);
if(!minFlow) return 0;
}
maxFlow+=minFlow;
minCost+=1ll*minFlow*D[t];
for(int x=t;x!=s;x=tata[x])
capacity[tata[x]][x]-=minFlow,
capacity[x][tata[x]]+=minFlow;
return 1;
}
pair<int,int>FMCM()
{
BellmanFord();
while(Dijkstra());
return {maxFlow,minCost};
}
int main()
{
int i,x,y,c,z;
fin>>n>>m>>s>>t;
while(m--)
fin>>x>>y>>c>>z,
g[x].push_back(y),
g[y].push_back(x),
capacity[x][y]+=c,
cost[x][y]=z,
cost[y][x]=-z;
fout<<FMCM().second;
return 0;
}