Pagini recente » Cod sursa (job #1046741) | Cod sursa (job #849354) | Cod sursa (job #848127) | Cod sursa (job #2933782) | Cod sursa (job #2693787)
#include<bits/stdc++.h>
using namespace std;
#define N 360
#define fi first
#define se second
#define INF 3500010
vector<long long> v[N];
long long adj[N][N], n, m, s, d, path[N], cost[N][N], dist[N], false_dist[N];
bool in_queue[N];
void bellmanford(){
queue<int> q;
vector<bool> in_queue(n+2, 0);
for(int i = 1;i<=n;i++){
dist[i] = INF;
}
dist[s] = 0;
q.push(s);
in_queue[s] = 1;
while(!q.empty()){
int curr = q.front();
q.pop();
in_queue[curr] = 0;
for(auto next: v[curr]){
if(adj[curr][curr] && dist[next] > dist[curr] + cost[curr][next]){
dist[next] = dist[curr] + cost[curr][next];
if(!in_queue[next]){
q.push(next);
in_queue[next] = 1;
}
}
}
}
}
struct cmp{
bool operator() (int i, int j) const{
return false_dist[i] > false_dist[j];
}
};
priority_queue <int, vector<int>, cmp> q;
bool dijkstra(){
for(int i = 1;i<=n;i++){
false_dist[i] = INF;
in_queue[i] = 0;
path[i] = 0;
}
false_dist[s] = 0;
path[s] = -1;
q.push(s);
in_queue[s] = 1;
while(!q.empty()){
int curr = q.top();
q.pop();
in_queue[curr] = 0;
for(auto next: v[curr]){
if(adj[curr][next] && false_dist[next] > false_dist[curr] + cost[curr][next] + dist[curr] - dist[next]){
false_dist[next] = false_dist[curr] + cost[curr][next] + dist[curr] - dist[next];
path[next] = curr;
if(!in_queue[next]){
in_queue[next] = 1;
q.push(next);
}
}
}
}
return path[d];
}
int mfmc(){
long long ans = 0;
while(dijkstra()){
int curr = d;
long long flow = INF;
while(path[curr] != -1){
flow = min(flow, adj[path[curr]][curr]);
curr = path[curr];
}
curr = d;
while(path[curr] != -1){
adj[path[curr]][curr] -= flow;
adj[curr][path[curr]] += flow;
ans+=flow*cost[path[curr]][curr];
curr = path[curr];
}
}
return ans;
}
int main(){
ifstream cin("fmcm.in");
ofstream cout("fmcm.out");
cin>>n>>m>>s>>d;
for(int i = m;i;i--){
int a,b,c,z;
cin>>a>>b>>c>>z;
v[a].push_back(b);
v[b].push_back(a);
adj[a][b] = c;
cost[a][b] = z;
cost[b][a] = -z;
}
bellmanford();
cout<<mfmc();
return 0;
}