Pagini recente » Cod sursa (job #2034037) | Cod sursa (job #2277818) | Cod sursa (job #2147018) | Cod sursa (job #1091653) | Cod sursa (job #2238459)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#define nmax 355
using namespace std;
ifstream f("fmcm.in");
ofstream g("fmcm.out");
int n,m, viz[nmax], fx[nmax][nmax], cp[nmax][nmax], cost[nmax][nmax], t[nmax], d[nmax], sur,dest, C;
vector <int> v[nmax];
queue <int> q;
void citire()
{
int i,j,k,cap,cst;
f>>n>>m>>sur>>dest;
for(k=1; k<=m; k++)
{
f>>i>>j>>cap>>cst;
v[i].push_back(j);
v[j].push_back(i);
cp[i][j]=cap;
cost[i][j]=cst; cost[j][i]=-cst;
}
}
int bellman_ford()
{
int i,nod;
for(i=1; i<=n; i++)
{d[i]=1e9; t[i]=0; viz[i]=0;}
d[sur]=0;
q.push(sur);
while(!q.empty())
{
nod=q.front();
q.pop();
viz[nod]++;
if(viz[nod]==n)
return (d[dest]!=1e9);
for(i=0; i<v[nod].size(); i++)
if( cp[nod][v[nod][i]]>fx[nod][v[nod][i]] && cost[nod][v[nod][i]]+d[nod]<d[v[nod][i]] )
{
d[v[nod][i]]=cost[nod][v[nod][i]]+d[nod];
q.push(v[nod][i]);
t[v[nod][i]]=nod;
}
}
return (d[dest]!=1e9);
}
int flux()
{
int nod, fmin;
while(bellman_ford())
{
fmin=1e9;
for(nod=dest; nod!=sur; nod=t[nod])
fmin=min(fmin, cp[t[nod]][nod]-fx[t[nod]][nod]);
for(nod=dest; nod!=sur; nod=t[nod])
{
fx[t[nod]][nod]+= fmin;
fx[nod][t[nod]]-= fmin;
}
C+= d[dest]*fmin;
}
return C;
}
int main()
{
citire();
g<<flux();
f.close();
g.close();
return 0;
}