Pagini recente » Cod sursa (job #162565) | Cod sursa (job #490670) | Cod sursa (job #514550) | Cod sursa (job #537095) | Cod sursa (job #2629948)
#include <iostream>
#include <cstdio>
#include <vector>
#include <queue>
using namespace std;
const int NMAX = 350;
const int MMAX = 12500;
const int FMAX = 1000000000;
const int CMAX = 1000000000;
struct elem {
int nod, cost, idx; /// idx - indicele muchiei prin care se ajunge la nod
elem(int cnod = 0, int ccost = 0, int cidx = 0) : nod(cnod), cost(ccost), idx(cidx) {}
};
bool operator > (elem e1, elem e2) {
return e1.cost > e2.cost;
}
int n, m, s, d, ctot;
int from[NMAX + 5];
int mind[NMAX + 5], reald[NMAX + 5];
int bfd[NMAX + 5];
int cf[NMAX + 5][NMAX + 5], cost[NMAX + 5][NMAX + 5];
vector<int> v[NMAX + 5];
priority_queue<elem, vector<elem>, greater<elem>> pq;
bool in_queue[NMAX + 5];
queue<int> q;
void bellman_ford(int start) {
for(int i = 1; i <= n; i++)
bfd[i] = CMAX;
q.push(start);
in_queue[start] = true;
bfd[start] = 0;
while(!q.empty()) {
int crt = q.front();
q.pop();
in_queue[crt] = false;
for(int vec: v[crt]) {
if(cf[crt][vec] == 0)
continue;
int new_d = bfd[crt] + cost[crt][vec];
if(new_d < bfd[vec]) {
bfd[vec] = new_d;
if(!in_queue[vec]) {
q.push(vec);
in_queue[vec] = true;
}
}
}
}
}
bool dijkstra(int start) {
bool vizd = false;
for(int i = 1; i <= n; i++) {
mind[i] = CMAX;
from[i] = -1;
}
pq.push(elem(start, 0, -1));
mind[start] = 0;
reald[start] = 0;
while(!pq.empty()) {
elem crt = pq.top();
pq.pop();
if(crt.cost > mind[crt.nod])
continue;
if(crt.nod == d) {
vizd = true;
continue;
}
for(int vec: v[crt.nod]) {
if(cf[crt.nod][vec] <= 0)
continue;
int new_d = crt.cost + cost[crt.nod][vec] + bfd[crt.nod] - bfd[vec];
if(new_d < mind[vec]) {
pq.push(elem(vec, new_d, crt.nod));
mind[vec] = new_d;
reald[vec] = reald[crt.nod] + cost[crt.nod][vec];
from[vec] = crt.nod;
}
}
}
for(int i = 1; i <= n; i++)
bfd[i] = reald[i];
return vizd;
}
void add_flux() {
int fmin = FMAX;
for(int nod = d; from[nod] != -1; nod = from[nod])
fmin = min(fmin, cf[from[nod]][nod]);
for(int nod = d; from[nod] != -1; nod = from[nod]) {
cf[from[nod]][nod] -= fmin;
cf[nod][from[nod]] += fmin;
}
ctot += fmin * reald[d];
}
int main() {
freopen("fmcm.in", "r", stdin);
freopen("fmcm.out", "w", stdout);
scanf("%d %d %d %d", &n, &m, &s, &d);
for(int i = 0; i < m; i++) {
int x, y, z, t;
scanf("%d %d %d %d", &x, &y, &z, &t);
cf[x][y] = z;
cost[x][y] = t;
v[x].push_back(y);
cf[y][x] = 0;
cost[y][x] = -t;
v[y].push_back(x);
}
bellman_ford(s);
while(dijkstra(s))
add_flux();
printf("%d", ctot);
return 0;
}