Pagini recente » Cod sursa (job #505823) | Cod sursa (job #194656) | Cod sursa (job #415728) | Istoria paginii runda/drumarb2 | Cod sursa (job #751381)
Cod sursa(job #751381)
#include <queue>
#include <vector>
#include <fstream>
#include <cstdlib>
#include <algorithm>
using namespace std;
typedef pair<int, int> pr;
const int N_MAX=400;
const int oo=1<<29;
bool was[N_MAX];
int F[N_MAX][N_MAX], C[N_MAX][N_MAX], d[N_MAX], f[N_MAX];
vector<pr> G[N_MAX];
vector<pr>::const_iterator it, iend;
class cmp {
public: bool operator() (const int& x, const int& y) {return d[x] > d[y];}
};
priority_queue<int, vector<int>, cmp > pQ;
inline int _min(int x, int y) {return x <= y ? x : y;}
bool BellmanFord(int source, int sink, int N)
{
int x, y;
for(x=1; x <= N; ++x)
{
f[x]=-1;
d[x]=oo;
was[x]=0;
}
d[source]=0;
for(pQ.push(source); !pQ.empty();)
{
x=pQ.top(); pQ.pop();
y=d[x];
was[x]=true;
for(it=G[x].begin(), iend=G[x].end(); it < iend; ++it)
if(d[it->first] > it->second + y && C[x][it->first] > F[x][it->first])
{
d[it->first]=it->second+y;
f[it->first]=x;
if(false == was[it->first])
{
pQ.push(it->first);
was[it->first]=true;
}
}
}
return oo != d[sink];
}
int main()
{
int N, M, source, sink, x, y, c, cost, s, cMin;
ifstream in("fmcm.in");
ofstream out("fmcm.out");
for(in>>N>>M>>source>>sink; M; --M)
{
in>>x>>y>>c>>cost;
G[x].push_back(pr(y,cost));
G[y].push_back(pr(x,-cost));
C[x][y]=c;
}
s=0;
while(BellmanFord(source, sink, N))
{
cMin=oo;
f[source]=-1;
for(x=sink; -1 != f[x]; x=f[x])
cMin=_min(cMin, C[f[x]][x] - F[f[x]][x]);
for(x=sink; -1 != f[x]; x=f[x])
{
F[x][f[x]]-=cMin;
F[f[x]][x]+=cMin;
}
s+=cMin*d[sink];
}
out<<s<<"\n";
return EXIT_SUCCESS;
}