Pagini recente » Cod sursa (job #1705664) | Statistici FII Irinel Manolache (Iri00) | Cod sursa (job #1656945) | Cod sursa (job #105747) | Cod sursa (job #1374263)
#include<fstream>
#include<vector>
#include<queue>
#include<cstring>
#include<algorithm>
#define Nmax 355
#define inf 0x3f3f3f3f
using namespace std;
ifstream in("fmcm.in");
ofstream out("fmcm.out");
int D[Nmax], D2[Nmax];
struct cmp
{
bool operator() (const pair<int, int> &x, const pair<int, int> &y)
{
return D2[x.first] > D2[y.first];
}
};
priority_queue<pair<int, int>, vector<pair<int, int> >, cmp> PQ;
vector<int> G[Nmax];
int Flow[Nmax][Nmax], Capacity[Nmax][Nmax], Cost[Nmax][Nmax], parent[Nmax];
bool dijkstra(int source, int destination)
{
bool inQueue[Nmax];
memset(D2, inf, sizeof(D2));
D2[source] = 0;
PQ.push(make_pair(source, 0));
while (!PQ.empty())
{
int node = PQ.top().first;
int lastNode = PQ.top().second;
PQ.pop();
if (parent[node] != lastNode) continue;
for (int i = 0; i < G[node].size(); i++)
{
int nextNode = G[node][i];
int cost = Cost[node][nextNode];
int newCost = D[node] - D[nextNode] + cost;
if (Flow[node][nextNode] < Capacity[node][nextNode] && D2[node] + newCost < D2[nextNode] )
{
parent[nextNode] = node;
D2[nextNode] = D2[node] + newCost;
PQ.push(make_pair(nextNode, node));
}
}
}
if (D2[destination] != inf) return true;
return false;
}
void bellmanFord(int source)
{
queue<int> Q;
bool inQueue[Nmax];
memset(D, inf, sizeof(D));
memset(inQueue, false, sizeof(inQueue));
inQueue[source] = true;
D[source] = 0;
Q.push(source);
while (!Q.empty())
{
int node = Q.front();
Q.pop();
for (int i = 0; i < G[node].size(); i++)
{
int nextNode = G[node][i];
int cost = Cost[node][nextNode];
if (Capacity[node][nextNode] && D[node] + cost < D[nextNode])
{
D[nextNode] = D[node] + cost;
if (!inQueue[nextNode])
{
Q.push(nextNode);
inQueue[nextNode] = true;
}
}
}
inQueue[node] = false;
}
}
int main()
{
int N, M, source, destination;
in >> N >> M >> source >> destination;
for (int i = 1; i <= M; i++)
{
int x, y, c, z;
in >> x >> y >> c >> z;
G[x].push_back(y);
G[y].push_back(x);
Capacity[x][y] = c;
Cost[x][y] = z;
Cost[y][x] = -z;
}
bellmanFord(source);
int totalCost = 0;
while (dijkstra(source, destination))
{
int node = destination, flow = inf, cost = 0;
while (node != source)
{
flow = min(flow, Capacity[parent[node]][node] - Flow[parent[node]][node]);
node = parent[node];
}
node = destination;
while (node != source)
{
Flow[parent[node]][node] += flow;
Flow[node][parent[node]] -= flow;
cost += flow * Cost[parent[node]][node];
node = parent[node];
}
totalCost += cost;
}
out << totalCost << "\n";
}