Pagini recente » Cod sursa (job #1983266) | Cod sursa (job #2427378) | Cod sursa (job #2975782) | Cod sursa (job #2542955) | Cod sursa (job #2961359)
#include <iostream>
#include <algorithm>
#include <fstream>
#include <vector>
#include <queue>
const short magic = 351;
const short inf = 1002;
const short MAX_CAPACITY = 10001;
std::vector<std::vector<int>> v(magic);
std::vector<std::vector<int>> capaci(magic, std::vector<int>(magic, 0));
std::vector<std::vector<int>> greutate(magic, std::vector<int>(magic, 0));
std::vector<int> generator(magic);
std::vector<int> distFord(magic, inf);
void bellmanFord(int start, int stop)
{
std::queue<int> q;
q.push(start);
std::vector<bool> in_coada(magic, 0);
distFord.assign(magic, inf);
distFord[start] = 0;
generator[start] = start;
in_coada[start] = 1;
while (!q.empty())
{
int nod = q.front();
q.pop();
in_coada[nod] = 0;
for (auto &&vec : v[nod])
{
if (capaci[nod][vec] and distFord[nod] + greutate[nod][vec] < distFord[vec])
{
distFord[vec] = distFord[nod] + greutate[nod][vec];
generator[vec] = nod;
if (in_coada[vec] == 0)
{
q.push(vec);
in_coada[vec] = 1;
}
}
}
}
}
int bfsBottleneck(int start, int end)
{
int minCost = 0;
int neck = MAX_CAPACITY;
int nod = end;
while (nod != start)
{
neck = std::min(neck, capaci[generator[nod]][nod]);
nod = generator[nod];
}
nod = end;
while (nod != start)
{
minCost += neck * greutate[generator[nod]][nod];
capaci[nod][generator[nod]] += neck;
capaci[generator[nod]][nod] -= neck;
nod = generator[nod];
}
return minCost;
}
int main()
{
// std::ifstream cin(".in");
std::ifstream cin("fmcm.in");
std::ofstream cout("fmcm.out");
short n, m, s, d;
cin >> n >> m >> s >> d;
for (size_t i = 0; i < m; i++)
{
int x, y, cap, cost;
cin >> x >> y >> cap >> cost;
v[x].push_back(y);
v[y].push_back(x);
capaci[x][y] = cap;
greutate[x][y] = cost;
greutate[y][x] = -cost;
}
int costTotal = 0;
while (1)
{
bellmanFord(s, d);
if (distFord[d] == inf)
{
break;
}
costTotal += bfsBottleneck(s, d);
}
cout << costTotal << '\n';
// std::cout << costTotal << '\n';
}