Pagini recente » Cod sursa (job #3216951) | Cod sursa (job #863730) | Cod sursa (job #2815122) | Cod sursa (job #1534500) | Cod sursa (job #3039899)
#include <algorithm>
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>
#include <queue>
#include <iomanip>
#define pii pair <int, int>
using namespace std;
string filename = "fmcm";
#ifdef LOCAL
ifstream fin("input.in");
ofstream fout("output.out");
#else
ifstream fin(filename + ".in");
ofstream fout(filename + ".out");
#endif
const int NMAX = 350;
const int INF = 1e9;
int n, m;
vector <pii> adj[NMAX + 1];
int flow[NMAX + 1][NMAX + 1];
int aux[NMAX + 1];
bool inQ[NMAX + 1];
void BF(int source){
for(int i = 1; i <= n; i++){
aux[i] = INF, inQ[i] = false;
}
queue <int> Q;
Q.push(source);
inQ[source] = true;
aux[source] = 0;
while(!Q.empty()){
int node = Q.front();
Q.pop();
inQ[node] = false;
for(pii vec : adj[node]){
if(aux[node] + vec.second < aux[vec.first] && flow[node][vec.first] > 0){
aux[vec.first] = aux[node] + vec.second;
if(!inQ[vec.first]){
Q.push(vec.first);
}
}
}
}
}
bool viz[NMAX + 1];
int parent[NMAX + 1];
int fakedist[NMAX + 1];
int realdist[NMAX + 1];
priority_queue <pii, vector <pii>, greater <pii>> pq;
bool DJK(int source, int destination){
for(int i = 1; i <= n; i++){
viz[i] = false;
fakedist[i] = realdist[i] = INF;
}
while(!pq.empty()){
pq.pop();
}
fakedist[source] = realdist[source] = 0;
pq.push({fakedist[source], source});
while(!pq.empty()){
int node = pq.top().second;
pq.pop();
if(!viz[node]){
viz[node] = true;
for(pii vec : adj[node]){
if(flow[node][vec.first] > 0 && fakedist[node] + vec.second + aux[node] - aux[vec.first] < fakedist[vec.first]){
fakedist[vec.first] = fakedist[node] + vec.second + aux[node] - aux[vec.first];
realdist[vec.first] = realdist[node] + vec.second;
parent[vec.first] = node;
pq.push({fakedist[vec.first], vec.first});
}
}
}
}
return (fakedist[destination] != INF);
}
signed main(){
int s, d;
fin >> n >> m >> s >> d;
for(int i = 1; i <= m; i++){
int a, b, c, d;
fin >> a >> b >> c >> d;
adj[a].push_back({b, +d});
adj[b].push_back({a, -d});
flow[a][b] = +c;
}
BF(s);
int maxFlow = 0;
int minCost = 0;
while(DJK(s, d)){
int mini = INF, node = d;
while(node != s){
mini = min(mini, flow[parent[node]][node]);
node = parent[node];
}
if(mini == 0){
continue;
}
node = d;
while(node != s){
flow[parent[node]][node] -= mini;
flow[node][parent[node]] += mini;
node = parent[node];
}
maxFlow += mini;
minCost += mini * realdist[d];
}
fout << minCost << '\n';
return 0;
}