Pagini recente » Cod sursa (job #1502832) | Cod sursa (job #788079) | Cod sursa (job #666312) | Cod sursa (job #1502645)
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
const int NMAX = 355;
const int inf = 1e9 + 5;
int n, m, s, t;
vector <int> graph[NMAX];
int cap[NMAX][NMAX];
int cost[NMAX][NMAX];
int father[NMAX];
int dist[NMAX];
queue <int> coada;
bool in_queue[NMAX];
inline bool bellman () {
for (int i = 1; i <= n; ++ i) {
in_queue[i] = false;
father[i] = 0;
dist[i] = inf;
}
coada.push(s);
in_queue[s] = true;
dist[s] = 0;
int y;
while (!coada.empty()) {
y = coada.front();
coada.pop();
for (auto it: graph[y])
if (cap[y][it] && dist[y] + cost[y][it] < dist[it]) {
dist[it] = dist[y] + cost[y][it];
father[it] = y;
if (!in_queue[it]) {
in_queue[it] = true;
coada.push(it);
}
}
}
return dist[t] < inf;
}
inline int mincost_flow () {
int flow = 0;
int suma = 0;
while (bellman()) {
int node = t;
int minim = inf;
while (father[node]) {
if (cap[father[node]][node] < minim)
minim = cap[father[node]][node];
node = father[node];
}
flow += minim;
node = t;
while (father[node]) {
cap[father[node]][node] -= minim;
cap[node][father[node]] += minim;
suma += minim * cost[father[node]][node];
node = father[node];
}
}
return suma;
}
int main()
{
ifstream cin("fmcm.in");
ofstream cout("fmcm.out");
cin >> n >> m >> s >> t;
int x, y, c, d;
while (m --) {
cin >> x >> y >> c >> d;
cap[x][y] = c;
cost[x][y] = d;
cost[y][x] = -d;
graph[x].push_back(y);
graph[y].push_back(x);
}
cout << mincost_flow() << '\n';
cin.close();
cout.close();
return 0;
}