Pagini recente » Cod sursa (job #1288306) | Cod sursa (job #2684513)
//fmcm
#include<bits/stdc++.h>
#define mp make_pair
#define N 510
#define Dim 2000000000
using namespace std;
vector <int> G[N];
queue <int> q;
int Cost[N][N],C[N][N],dist[N],dp[N],newdist[N],pred[N],f[N][N],viz[N];
int n,m,s,d;
void read()
{
freopen("fmcm.in","r",stdin);
int i,x,y,z,cost;
scanf("%d%d%d%d",&n,&m,&s,&d);
for(i=1;i<=m;i++)
{
scanf("%d%d%d%d",&x,&y,&z,&cost);
G[x].push_back(y);
G[y].push_back(x);
Cost[x][y]=cost;
Cost[y][x]=-cost;
C[x][y]=z; //capacitatea
}
}
bool still;
priority_queue<pair<int, int>, vector<pair<int, int> >, greater<pair<int, int> > > pq;
inline bool b_ford()
{
int i,j,nod;
for(i = 1; i <= n; ++i)
dist[i] = Dim;
dist[s] = 0;
memset(viz,0,sizeof(viz));
q.push(s);
viz[s] = 1;
while(!q.empty())
{
nod=q.front();
q.pop();
for(j=0;j<G[nod].size();j++)
if(C[nod][G[nod][j]] && dist[nod]+Cost[nod][G[nod][j]]<dist[G[nod][j]])
{
dist[G[nod][j]]=dist[nod]+Cost[nod][G[nod][j]];
if(!viz[G[nod][j]])
{
q.push(G[nod][j]);
viz[G[nod][j]]=1;
}
}
viz[nod]=0;
}
return (dist[d] != Dim);
}
int Edmonds_Karp()
{
int i;
for(i = 1; i <= n; ++i){
pred[i] = -1;
newdist[i] = Dim;
}
newdist[s] = 0;
memset(viz,0,sizeof(viz));
pq.push(mp(0,s));
while(!pq.empty())
{
auto nod = pq.top();
pq.pop();
if(viz[nod.second])
continue;
viz[nod.second] = 1;
for(auto& it: G[nod.second])
if(C[nod.second][it] > f[nod.second][it])
{
int distance = nod.first + Cost[nod.second][it] + dist[nod.second] - dist[it];
if(distance < newdist[it]){
//cerr<<it<<' '<<distance<<'\n';
newdist[it] = distance;
pred[it] = nod.second;
if(!viz[it])
pq.push(mp(newdist[it],it));
}
}
viz[nod.second]=0;
}
//cerr<<newdist[d]<<' '<<dist[d]<<'\n';
if(newdist[d] != Dim)
{
//cout<<dist[d]<<endl;
still = 1;
int aleg = Dim;
for(i = d; i != s; i = pred[i])
aleg = min(aleg, C[pred[i]][i] - f[pred[i]][i]);
for(i = d; i != s; i = pred[i])
{
f[pred[i]][i] += aleg;
f[i][pred[i]] -= aleg;
}
return aleg * (newdist[d] + dist[d]);
}
return 0;
}
long long answer()
{
long long R = 0;
still = 1;
b_ford();
while(still)
{
still = 0;
R += Edmonds_Karp()*1ll;
//cout<<R<<endl;
}
return R;
}
int main()
{
read();
freopen("fmcm.out","w",stdout);
cout<<answer();
}