Pagini recente » Cod sursa (job #3151493) | Cod sursa (job #1833455) | Cod sursa (job #2474185) | Cod sursa (job #2229954) | Cod sursa (job #914581)
Cod sursa(job #914581)
#include <cstdio>
#include <vector>
#include <string>
#include <bitset>
#include <queue>
#include <fstream>
#include <string.h>
#include <math.h>
#include <algorithm>
#define fcat(c) while (c!='\n') fscanf(f,"%c",&c)
#define cat(c) while (c!='\n') scanf("%c",&c)
#define For(i,st,dr,k) for (int i=(st);i<=(dr);i+=(k))
#define ll (long long)
#define INF 1000000
#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
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;
vector<int>::iterator j;
for (i=1;i<=n;i++)
D[i]=INF;
D[st]=0;
q.push(st);
while (q.size()>0)
{
i=q.front();
q.pop();
in_q[i]=0;
for (j=e[i].begin();j!=e[i].end();j++)
if (kfl(i,*j)>0 && D[i]+a[i][*j].z<D[*j])
{
D[*j]=D[i]+a[i][*j].z;
if (!in_q[*j])
{
in_q[*j]=1;
q.push(*j);
}
}
}
sum=D[dr];
for (i=1;i<=n;i++)
for (j=e[i].begin();j!=e[i].end();j++)
a[i][*j].z=D[i]+a[i][*j].z-D[*j];
}
int dijkstra()
{
int i,x,mn,aj;
vector <int>::iterator j;
for (i=1;i<=n;i++) dist[i]=INF,TT[i]=-1;
dist[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=e[i].begin();j!=e[i].end();j++)
if (kfl(i,*j)>0 && dist[i]+a[i][*j].z<dist[*j])
{
dist[*j]=dist[i]+a[i][*j].z;
TT[*j]=i;
H.push(make_pair(-dist[*j],*j));
}
}
while (H.size()) H.pop();
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;
ans+=(sum+dist[dr])*mn;
return 1;
}
int main()
{
read();
bellman();
while (dijkstra());
g<<ans;
return 0;
}