Pagini recente » Cod sursa (job #1711629) | Cod sursa (job #2639376) | Cod sursa (job #2877742) | Cod sursa (job #1929690) | Cod sursa (job #926278)
Cod sursa(job #926278)
#include <cstdio>
#include <vector>
#include <string>
#include <bitset>
#include <queue>
#include <fstream>
#include <string.h>
#include <math.h>
#include <algorithm>
#define INF 1048576
#define kfl(i,j) a[i][j].c-a[i][j].f
using namespace std;
int D[400];
struct cp{int f,c,z;
cp() {};
cp(int aa,int bb,int cc)
{f=aa; c=bb; z=cc;}
};
cp a[355][355];
vector <int> e[355];
priority_queue <pair<int,int> > H; //dijkstra
int dist[400]; //dijkstra
int TT[400]; //flux in dijkstra
bool in_q[355]; //bellman
int R[400];
queue <int> q;
int n,m,st,dr;
int flux,ans,sum ; // sum repr costul minim acum
ifstream f("fmcm.in");
ofstream g("fmcm.out");
void read()
{
int i,x,y,cap,z;
f>>n>>m>>st>>dr;
for (i=1;i<=m;i++)
{
f>>x>>y>>cap>>z;
a[x][y]=cp(0,cap,z);
a[y][x]=cp(0,0,-z);
e[x].push_back(y);
e[y].push_back(x);
}
}
void bellman()
{
int i,j;
for (i=1;i<=n;i++)
D[i]=INF;
in_q[st]=true;
D[st]=0;
q.push(st);
while (q.size()>0)
{
i=q.front();
q.pop();
in_q[i]=false;
for (j=0;j<e[i].size();j++)
if (kfl(i,e[i][j])>0 && D[i]+a[i][e[i][j]].z<D[e[i][j]])
{
D[e[i][j]]=D[i]+a[i][e[i][j]].z;
if (!in_q[e[i][j]])
{
in_q[e[i][j]]=true;
q.push(e[i][j]);
}
}
}
sum=D[dr];
}
int dijkstra()
{
int i,j,x,mn,aj;
for (i=1;i<=n;i++) dist[i]=INF,TT[i]=-1;
dist[st]=0;
R[st]=0;
H.push(make_pair(0,st));
while (H.size())
{
if (H.top().first==INF) break;
i=H.top().second;
aj=-H.top().first;
H.pop();
if (aj>dist[i]) continue;
for (j=0;j<e[i].size();j++)
if (kfl(i,e[i][j])>0 && dist[i]+D[i]+a[i][e[i][j]].z-D[e[i][j]]<dist[e[i][j]])
{
dist[e[i][j]]=dist[i]+D[i]+a[i][e[i][j]].z-D[e[i][j]];
TT[e[i][j]]=i;
R[e[i][j]]=R[i]+a[i][e[i][j]].z;
H.push(make_pair(-dist[e[i][j]],e[i][j]));
}
}
while (H.size()) H.pop();
memcpy(D, R, sizeof(R));
if (TT[dr]==-1) return 0;
for (mn=INF,x=dr;x!=st;x=TT[x]) mn=min(mn,kfl(TT[x],x));
for (x=dr;x!=st;x=TT[x])
{
a[TT[x]][x].f+=mn;
a[x][TT[x]].f-=mn;
}
flux+=mn;
sum+=dist[dr];
ans+=sum*mn;
return 1;
}
int main()
{
read();
bellman();
while (dijkstra());
g<<ans;
return 0;
}