Pagini recente » Cod sursa (job #1373278) | Cod sursa (job #703863)
Cod sursa(job #703863)
#include <fstream>
#include <cstring>
#include <cstdlib>
#include <queue>
using namespace std;
ifstream in("fmcm.in");
ofstream out("fmcm.out");
const int N = 353;
const int oo = 0x3f3f3f3f;
int n, s, d;
int vis[N];
int fat[N];
int cost[N];
int f[N][N];
int c[N][N];
int p[N][N];
void Read()
{
int m;
in >> n >> m >> s >> d;
while (m--) {
int x, y, cc, z;
in >> x >> y >> cc >> z;
c[x][y] = cc;
p[x][y] = z;
p[y][x] = -z;
}
}
bool Road()
{
queue <int> q;
memset(vis, 0, sizeof(vis));
memset(cost, oo, sizeof(cost));
q.push(s);
vis[s] = 1;
cost[s] = 0;
while(!q.empty()) {
int node = q.front();
for (int i = 1; i <= n; ++i)
if (c[node][i] - f[node][i] > 0 && cost[i] > cost[node] + p[node][i]) {
cost[i] = cost[node] + p[node][i];
fat[i] = node;
++vis[i];
if (vis[i] == n)
return vis[d];
q.push(i);
}
q.pop();
}
return vis[d];
}
int Solve()
{
int totalPrice = 0;
while (Road())
{
int node = d;
int flow = oo;
while (node != s)
{
if (c[fat[node]][node] - f[fat[node]][node] < flow)
flow = c[fat[node]][node] - f[fat[node]][node];
node = fat[node];
}
node = d;
while (node != s)
{
f[fat[node]][node] += flow;
f[node][fat[node]] -= flow;
totalPrice += flow * p[fat[node]][node];
node = fat[node];
}
}
return totalPrice;
}
int main()
{
Read();
out << Solve() << "\n";
return 0;
}