Pagini recente » Cod sursa (job #281619) | Monitorul de evaluare | Cod sursa (job #2021106) | Cod sursa (job #2427040) | Cod sursa (job #1551083)
#include<cstdio>
#include<deque>
#include<cstring>
#include<queue>
#include<algorithm>
#include<vector>
const int nmax=350;
const int mmax=12500;
const int inf=2000000000;
using namespace std;
int n,m,s,t;
int flux[nmax+5][nmax+5];
int ca[nmax+5][nmax+5],co[nmax+5][nmax+5],ta[nmax+5],cv[nmax+5];
deque<int> que;
bool be[nmax+5],inq[nmax+5];
vector<int > ve[nmax+5];
struct sp
{
int y,co;
bool operator < (const sp & other) const
{
if(co!=other.co)
return co>other.co;
return y<other.y;
}
};
priority_queue<sp,vector<sp> > pq;
void belman()
{
int x,i;
memset(cv,inf,sizeof(cv));
cv[s]=0;
que.push_back(s);
inq[s]=1;
while(!que.empty())
{
x=que.back();
que.pop_back();
for(i=ve[x].size()-1; i>=0; i--)
if(ca[x][ve[x][i]]>0 && cv[x]+co[x][ve[x][i]]<cv[ve[x][i]])
{
cv[ve[x][i]]=cv[x]+co[x][ve[x][i]];
if(inq[ve[x][i]]==0)
{
inq[ve[x][i]]=1;
que.push_back(ve[x][i]);
}
}
inq[x]=0;
}
}
int oldd[nmax+5],newd[nmax+5],reald[nmax+5];
bool djkstra()
{
sp tm,tn;
int i,x;
for(i=1;i<=n;i++)
newd[i]=inf;
reald[s]=newd[s]=0;
tm.co=0;tm.y=s;pq.push(tm);
while(!pq.empty())
{
tm=pq.top();
pq.pop();
if(tm.co==newd[tm.y])
{
for(i=ve[tm.y].size()-1;i>=0;i--)
if(ca[tm.y][ve[tm.y][i]]-flux[tm.y][ve[tm.y][i]]>0)
{
x=newd[tm.y]+co[tm.y][ve[tm.y][i]]-(oldd[ve[tm.y][i]]-oldd[tm.y]);
if(x<newd[ve[tm.y][i]])
{
tn.y=ve[tm.y][i];
tn.co=newd[ve[tm.y][i]]=x;
ta[ve[tm.y][i]]=tm.y;
reald[ve[tm.y][i]]=reald[tm.y]+co[tm.y][ve[tm.y][i]];
pq.push(tn);
}
}
}
}
for(i=1;i<=n;i++)
oldd[i]=newd[i];
if(newd[t]!=inf)
return 1;
else
return 0;
}
void da()
{
int i,cmin,z;
belman();
for(i=1;i<=n;i++)
oldd[i]=cv[i];
while(djkstra())
{
cmin=-1;
z=t;
while(z!=s)
{
if(ca[ta[z]][z]-flux[ta[z]][z]<cmin || cmin==-1)
cmin=ca[ta[z]][z]-flux[ta[z]][z];
z=ta[z];
}
z=t;
while(z!=s)
{
flux[ta[z]][z]+=cmin;
flux[z][ta[z]]-=cmin;
z=ta[z];
}
}
}
int main()
{
freopen("fmcm.in","r",stdin);
freopen("fmcm.out","w",stdout);
int i,j,x,y,cmin;
scanf("%d%d%d%d",&n,&m,&s,&t);
for(i=1; i<=m; i++)
{
scanf("%d%d",&x,&y);
scanf("%d%d",&ca[x][y],&co[x][y]);
co[y][x]=-co[x][y];
ve[x].push_back(y);
ve[y].push_back(x);
}
da();
cmin=0;
for(i=1; i<=n; i++)
for(j=1; j<=n; j++)
if(flux[i][j]>0)
{
cmin=cmin+flux[i][j]*co[i][j];
}
printf("%d\n",cmin);
return 0;
}