Pagini recente » Cod sursa (job #3231490) | Cod sursa (job #736965) | Cod sursa (job #145366) | Cod sursa (job #2958735) | Cod sursa (job #567860)
Cod sursa(job #567860)
#include <cstdio>
#include <vector>
#include <cstring>
#define MaxN 355
#define MAX 1000005
#define Inf 2000000000
#define infile "fmcm.in"
#define outfile "fmcm.out"
using namespace std;
vector <int> G[MaxN];
int cap[MaxN][MaxN],cost[MaxN][MaxN],b[MaxN][MaxN];
int t[MaxN],Q[MAX],uz[MaxN],dist[MaxN];
int N,M,S,D,sw=1,MIN;
long long CT;
void add(int x,int y)
{
G[x].push_back(y);
}
void read()
{
int i,x,y,c,z;
scanf("%d%d%d%d",&N,&M,&S,&D);
for(i=1;i<=M;i++)
{
scanf("%d%d%d%d",&x,&y,&c,&z);
add(x,y); add(y,x);
cap[x][y]=c; cost[x][y]=z;
cost[y][x]=-z;
}
}
void BF()
{
int i,p=1,j,x,nr,y;
for(i=1;i<=N;i++)
dist[i]=Inf, t[i]=-1;
sw=0;
dist[S]=0;
Q[p]=S; uz[S]=1;
for(i=1;i<=p;i++)
{
x=Q[i]; nr=G[x].size();
for(j=0;j<nr;j++)
{
y=G[x][j];
if(cap[x][y]-b[x][y]>0 && dist[x]+cost[x][y]<dist[y])
{
dist[y]=dist[x]+cost[x][y];
t[y]=x;
if(!uz[y])
{
Q[++p]=y;
uz[y]=1;
}
}
}
uz[x]=0;
}
if(dist[D]!=Inf)
sw=1;
}
void solve()
{
int nod;
do{
BF();
if(sw)
{
MIN=Inf;
nod=D;
while(nod!=S)
{
if(cap[t[nod]][nod]-b[t[nod]][nod]<MIN)
MIN=cap[t[nod]][nod]-b[t[nod]][nod];
nod=t[nod];
}
nod=D;
while(nod!=S)
{
b[t[nod]][nod]+=MIN;
b[nod][t[nod]]-=MIN;
CT+=(long long)(cost[t[nod]][nod]*MIN);
nod=t[nod];
}
}
}while(sw);
}
void write()
{
printf("%lld\n",CT);
}
int main()
{
freopen(infile,"r",stdin);
freopen(outfile,"w",stdout);
read();
solve();
write();
fclose(stdin);
fclose(stdout);
return 0;
}