Pagini recente » Cod sursa (job #3159162) | Cod sursa (job #2560250) | Cod sursa (job #2982216) | Cod sursa (job #2558537) | Cod sursa (job #2689611)
#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];
int curr_cost, node, new_dist;
int a, b, c, z;
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;
}
};
inline void Bellman(){
memset(vis, 0, sizeof(vis));
for (int i = 1; i <= n; ++i)
old_dist[i] = 1e9;
Q.push(s);
old_dist[s] = 0;
vis[s] = 1;
while (not Q.empty()){
node = Q.front();
curr_cost = old_dist[node];
Q.pop();
vis[node] = 0;
for (int nei: graph[node]){
if (!cap[node][nei])
continue;
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;
}
}
}
}
}
inline int Dijkstra(){
memset(vis, 0, sizeof(vis));
for (int i = 1; i <= n; ++i)
dist[i] = 1e9;
S.push({0, s});
dist[s] = 0;
while (not S.empty()){
auto nod = S.top();
S.pop();
curr_cost = -nod.first;
node = nod.second;
if (vis[node]){
continue;
}
vis[node] = 1;
if (curr_cost != dist[node])
continue;
for (int nei: graph[node]){
if (vis[nei])
continue;
if (!cap[node][nei])
continue;
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];
}
memcpy(old_dist, dist, sizeof(old_dist));
return path_cost * flow;
}
int main(){
InParser fin("fmcm.in");
ofstream fout("fmcm.out");
fin >> n >> m >> s >> d;
while (m--){
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;
}