Pagini recente » Cod sursa (job #3275396) | Cod sursa (job #1646199) | Cod sursa (job #2394803) | Cod sursa (job #3276179) | Cod sursa (job #730036)
Cod sursa(job #730036)
#include <fstream>
#include <vector>
#include <queue>
#include <bitset>
using namespace std;
#define foreach(V) for(typeof (V).begin() it = (V).begin(); it != (V).end(); ++it)
const int MAX_N = 355;
const int INF = 0x3f3f;
ifstream fin ("fmcm.in");
ofstream fout ("fmcm.out");
vector <short> G[MAX_N];
short C[MAX_N][MAX_N], F[MAX_N][MAX_N], T[MAX_N];
short D[MAX_N], Cost[MAX_N][MAX_N];
short N, M, P, U;
/**
* Read the data from the input file and create the vectors that contain the edges and the cost
*/
void read() {
fin >> N >> M >> P >> U;
while(M--)
{
short a, b, c, cost;
fin >> a >> b >> c >> cost;
G[a].push_back(b);
G[b].push_back(a);
C[a][b] = c;
Cost[a][b] = cost;
Cost[b][a] = -cost;
}
}
/**
* The comparation function for the priority queue, sorting the elements depending on the distance vector
*/
struct cmp {
bool operator()(const short &a, const short &b) {
return D[a] > D[b];
}
};
/**
* Return true if there is any flow from the source to the destination, and store the flow
*/
bool dijkstra() {
for(int i = 1; i <= N; ++i) {
D[i] = INF;
}
priority_queue <short, vector <short>, cmp > Q;
bitset <MAX_N> inq;
Q.push(P);
D[P] = 0;
inq[P] = 1;
while(!Q.empty()) {
short nod = Q.top();
Q.pop();
inq[nod] = 0;
foreach(G[nod]) {
if(C[nod][*it] > F[nod][*it] && D[nod] + Cost[nod][*it] < D[*it]) {
D[*it] = D[nod] + Cost[nod][*it];
T[*it] = nod;
if(inq[*it]) continue;
Q.push(*it);
inq[*it] = 1;
}
}
}
return (D[U] < INF);
}
/**
* Perform the flow algorithm
*/
void minFlow() {
int fmin, flow = 0;
while(dijkstra()) {
fmin = INF;
for(short i = U; i != P; i = T[i])
fmin = min(fmin, C[T[i]][i] - F[T[i]][i]);
for(short i = U; i != P; i = T[i]) {
F[T[i]][i] += fmin;
F[i][T[i]] -= fmin;
}
flow += fmin * D[U];
}
fout << flow;
}
int main() {
read();
minFlow();
}