Pagini recente » Cod sursa (job #2320094) | Cod sursa (job #3222106) | Cod sursa (job #3182603) | Cod sursa (job #2467687) | Cod sursa (job #2689602)
#include <bits/stdc++.h>
using namespace std;
const int N = 400;
int n, m, s, d;
vector <int> graph[N];
int cap[N][N], cost[N][N];
queue <int> Q;
priority_queue < pair <int, int> > S;
int old_dist[N], dist[N], pr[N];
bool vis[N];
class InParser{
private:
FILE *fin;
char *buff;
int sp;
char read_ch(){
++sp;
if (sp == 4096){
sp = 0;
fread(buff, 1, 4096, fin);
}
return buff[sp];
}
public:
InParser(const char* nume){
fin = fopen(nume, "r");
buff = new char[4096];
sp = 4095;
}
InParser& operator>> (int &n){
char c;
while (!isdigit(c = read_ch()) && c != '-');
int sgn = 1;
if (c == '-'){
n = 0;
sgn = -1;
}
else{
n = c - '0';
}
while(isdigit(c = read_ch())){
n = n * 10 + c - '0';
}
n *= sgn;
return *this;
}
};
void Bellman(){
for (int i = 1; i <= n; ++i){
old_dist[i] = 1e9;
vis[i] = 0;
}
Q.push(s);
old_dist[s] = 0;
vis[s] = 1;
while (not Q.empty()){
int node = Q.front();
int curr_cost = old_dist[node];
Q.pop();
vis[node] = 0;
for (int nei: graph[node]){
if (!cap[node][nei])
continue;
int new_dist = curr_cost + cost[node][nei];
if (new_dist < old_dist[nei]){
old_dist[nei] = new_dist;
if (!vis[nei]){
Q.push(nei);
vis[nei] = 1;
}
}
}
}
//for (int i = 1; i <= n; ++i)
// fout << old_dist[i] << ' ';
//fout << '\n';
}
int Dijkstra(){
for (int i = 1; i <= n; ++i)
dist[i] = 1e9;
S.push({0, s});
dist[s] = 0;
while (not S.empty()){
int curr_cost = -S.top().first;
int node = S.top().second;
S.pop();
if (curr_cost != dist[node])
continue;
for (int nei: graph[node]){
if (!cap[node][nei])
continue;
int new_dist = curr_cost + cost[node][nei] + old_dist[node] - old_dist[nei];
if (new_dist < dist[nei]){
dist[nei] = new_dist;
S.push({-dist[nei], nei});
pr[nei] = node;
}
}
}
if (dist[d] == 1e9)
return 0;
int flow = 1e9, path_cost = 0;
for (int node = d; node != s; node = pr[node])
flow = min(flow, cap[pr[node]][node]);
for (int node = d; node != s; node = pr[node]){
cap[pr[node]][node] -= flow;
cap[node][pr[node]] += flow;
path_cost += cost[pr[node]][node];
//fout << node << ' ';
}
//fout << " cost: " << path_cost << " flow: " << flow << '\n';
for (int i = 1; i <= n; ++i)
old_dist[i] = dist[i];
return path_cost * flow;
}
int main(){
InParser fin("fmcm.in");
ofstream fout("fmcm.out");
fin >> n >> m >> s >> d;
while (m--){
int a, b, c, z;
fin >> a >> b >> c >> z;
graph[a].push_back(b);
graph[b].push_back(a);
cap[a][b] = c;
cost[a][b] = z;
cost[b][a] = -z;
}
Bellman();
int ans = 0, path_cost = 0;
do{
path_cost = Dijkstra();
ans += path_cost;
} while(path_cost);
fout << ans << '\n';
return 0;
}