Pagini recente » Cod sursa (job #666787) | Cod sursa (job #1831087) | Cod sursa (job #1466977) | Istoria paginii runda/simulare-cartita-19b | Cod sursa (job #696675)
Cod sursa(job #696675)
#include <fstream>
#include <vector>
#define NMAX 357
#define INF 1<<28
using namespace std;
vector <int> G[NMAX];
int N,M,S,D,Sum,Drum,l;
int t[NMAX],c[NMAX][NMAX],cost[NMAX][NMAX],f[NMAX][NMAX],dist[NMAX],h[NMAX],pos[NMAX];
void BellmanFord(){
int i,j,stop;
for(i=1;i<=N;i++) dist[i]=INF;
dist[S]=0; stop=0;
for(i=1;i<=N && !stop;i++){
stop=1;
for(j=1;j<=N;j++)
for(vector<int>::iterator it=G[j].begin();it!=G[j].end();it++)
if(c[j][*it]-f[j][*it]>0 && dist[j]+cost[j][*it]<dist[*it]){
stop=0;
dist[*it]=dist[j]+cost[j][*it];
}
}
Sum=dist[D];
}
void upheap(int poz)
{
while(poz>=1 && dist[h[poz]]<dist[h[poz/2]])
{
swap(pos[h[poz]],pos[h[poz/2]]);
swap(h[poz],h[poz/2]);
poz=poz/2;
}
}
void downheap(int poz)
{
while(poz*2+1<=l && (dist[h[poz]]>dist[h[poz*2]] || dist[h[poz]]>dist[h[poz*2+1]]))
{
if(poz*2+1<=l && dist[h[poz*2]]>dist[h[poz*2+1]])
{
swap(pos[h[poz]],pos[h[poz*2+1]]);
swap(h[poz],h[poz*2+1]);
poz=poz*2+1;
}
else
{
swap(pos[h[poz]],pos[h[poz*2]]);
swap(h[poz],h[poz*2]);
poz=poz*2;
}
}
}
int Dijkstra(){
int i,nod=S;
for(i=1;i<=N;i++)
for(vector <int>::iterator it=G[i].begin();it!=G[i].end();it++)
if(dist[i]!=INF && dist[*it]!=INF) cost[i][*it]+=dist[i]-dist[*it];
for(i=1;i<=N;i++){
h[i]=i;
pos[i]=i;
dist[i]=INF;
}
l=N; dist[S]=0;
h[1]=S, h[S]=1;
pos[1]=S, pos[S]=1;
while(l&& dist[nod]!=INF){
nod=h[1];
h[1]=h[l--];
pos[h[1]]=1;
downheap(1);
for(vector<int>::iterator it=G[nod].begin();it!=G[nod].end();it++){
if(c[nod][*it]-f[nod][*it]>0 && dist[nod]+cost[nod][*it]<dist[*it]){
dist[*it]=dist[nod]+cost[nod][*it];
t[*it]=nod;
upheap(pos[*it]);
}
}
}
if(dist[D]!=INF){
int fmin=INF;
Drum=1;
for(i=D;i!=S;i=t[i])
fmin=min(fmin,c[t[i]][i]-f[t[i]][i]);
if(!fmin) return 0;
for(i=D;i!=S;i=t[i]){
f[t[i]][i]+=fmin;
f[i][t[i]]-=fmin;
}
Sum+=dist[D];
return fmin*Sum;
}
return 0;
}
long long Flux(){
long long Sol=0;
Drum=1;
while(Drum){
Drum=0;
Sol+=Dijkstra();
}
return Sol;
}
int main(){
int x,y,z,t;
ifstream in("fmcm.in");
ofstream out("fmcm.out");
in>>N>>M>>S>>D;
for(;M>0;M--){
in>>x>>y>>z>>t;
G[x].push_back(y);
G[y].push_back(x);
c[x][y]=z;
cost[x][y]=t;
cost[y][x]=-t;
}
BellmanFord();
out<<Flux()<<"\n";
in.close();
out.close();
return 0;
}