Pagini recente » Cod sursa (job #283090) | Cod sursa (job #2893106) | Cod sursa (job #3287584) | Monitorul de evaluare | Cod sursa (job #1551214)
#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];
priority_queue<pair<int,int> ,vector<pair<int,int> >,greater<pair<int, int> > > 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()
{
memset(newd, 0x3f, sizeof(newd));
newd[s] = 0; reald[s] = 0;
pq.push(make_pair(newd[s], s));
for (; !pq.empty(); )
{
int cst = pq.top().first, nod = pq.top().second;
pq.pop();
if (newd[nod] != cst)
continue;
vector<int> :: iterator it;
for (it = ve[nod].begin(); it != ve[nod].end(); it++)
if (ca[nod][*it]-flux[nod][*it])
{
int new_d = newd[nod] + co[nod][*it] + oldd[nod] - oldd[*it];
if (new_d < newd[*it])
{
newd[*it] = new_d;
reald[*it] = reald[nod] + co[nod][*it];
ta[*it] = nod;
pq.push(make_pair(newd[*it], *it));
}
}
}
memcpy(oldd, reald, sizeof(newd));
if (newd[t] == 0x3f3f3f3f)
return 0;
else
return 1;
}
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;
}