Pagini recente » Cod sursa (job #580005) | Cod sursa (job #1268504) | Cod sursa (job #2810804) | Cod sursa (job #1873596) | Cod sursa (job #2957970)
#include<iostream>
#include<fstream>
#include<queue>
#include<vector>
#include<unordered_map>
using namespace std;
int n, m, c, z, x, y, s, d;
priority_queue <pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>> > pq;
vector<vector<int>>lista;
int tati[351];
unordered_map<int, bool>label;
int flux[351][351];
int cost[351][351];
int distanta_B[351];
int distanta[351];
int distanta_r[351];
ifstream f("fmcm.in");
ofstream g("fmcm.out");
void Bellman_Ford() {
for (int i= 1; i <= n; i++)
distanta_B[i] = 10000000;
queue<int> q;
q.push(s);
distanta_B[s] = 0;
while (!q.empty()) {
int x = q.front();
q.pop();
label[x] = 0;
for (auto el : lista[x])
if(flux[x][el]>0)
if (cost[x][el] + distanta_B[x] < distanta_B[el])
{
distanta_B[el] = cost[x][el] + distanta_B[x];
if (label[el] == 0) {
label[el] = 1;
q.push(el);
}
}
}
}
bool Dijkstra() {
for (int i = 1; i <= n; i++)
{
distanta[i] = 1000000000;
}
distanta[s] = 0;
distanta_r[s] = 0;
pq.push({ 0,s });
while (!pq.empty()) {
int c = pq.top().first;
int x = pq.top().second;
label[x] = 1;
pq.pop();
if (distanta[x] == c) {
for (auto el : lista[x]) {
if (flux[x][el] > 0 && distanta[el] > distanta[x] + distanta_B[x] + cost[x][el] - distanta_B[el])
{
distanta[el] = distanta[x] + distanta_B[x] + cost[x][el] - distanta_B[el];
distanta_r[el] = distanta_r[x] + cost[x][el];
pq.push({ distanta[el],el });
tati[el] = x;
}
}
}
}
return distanta[d] != 1000000000;
}
int main() {
f >> n >> m >> s >> d;
int rez = 0;
lista.resize(n + 1);
for(int i=1;i<=m;i++)
{
f>> x >> y >> c >> z;
lista[x].push_back(y);
lista[y].push_back(x);
flux[x][y] = c;
cost[x][y] = z;
cost[y][x] = -z;
}
Bellman_Ford();
while (Dijkstra()) {
for (int i = 1; i <= n; i++)
distanta_B[i] = distanta_r[i];
int min1 = 100000000;
int x = d;
while (x != s) {
min1 = min(min1, flux[tati[x]][x]);
x = tati[x];
}
x = d;
while (x != s) {
flux[tati[x]][x] -= min1;
flux[x][tati[x]] += min1;
x = tati[x];
}
rez += min1 * distanta_r[d];
}
g<<rez;
}