Pagini recente » Cod sursa (job #1711181) | Cod sursa (job #1415926)
#include <fstream>
#include <vector>
#include <queue>
#define NMAX 355
#define MMAX 12505
#define inf (1 << 30)
using namespace std;
int n, m;
vector <int> graph[NMAX];
int cap[NMAX][NMAX];
int cost[NMAX][NMAX];
//Bellman
int dist[NMAX];
bool in_queue[NMAX];
int father[NMAX];
queue <int> _queue;
int s, t;
bool bellman () {
for (int i = 1; i <= n; i++) {
dist[i] = inf;
father[i] = 0;
}
dist[s] = 0;
in_queue[s] = true;
_queue.push(s);
int y;
vector <int> :: iterator it;
while (!_queue.empty()) {
y = _queue.front();
_queue.pop();
in_queue[y] = false;
for (it = graph[y].begin(); it != graph[y].end(); it++)
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;
_queue.push(*it);
}
}
}
return (dist[t] < inf);
}
int total_flow;
int total_cost;
inline void mincostflow () {
while (bellman()) {
int minima = cap[father[t]][t];
int node = t;
while (node != s) {
minima = min(minima, cap[father[node]][node]);
node = father[node];
}
total_flow += minima;
node = t;
while (node != s) {
cap[father[node]][node] -= minima;
cap[node][father[node]] += minima;
total_cost += cost[father[node]][node] * minima;
node = father[node];
}
}
}
int main()
{
ifstream cin("fmcm.in");
ofstream cout("fmcm.out");
cin >> n >> m >> s >> t;
int a, b, c, d;
while (m--) {
cin >> a >> b >> c >> d;
cap[a][b] += c;
cost[a][b] = d;
cost[b][a] = -d;
graph[a].push_back(b);
graph[b].push_back(a);
}
mincostflow();
cout << total_cost << '\n';
cin.close();
cout.close();
return 0;
}