Pagini recente » Cod sursa (job #3225236) | Cod sursa (job #1468107) | Cod sursa (job #2519298) | Cod sursa (job #46654) | Cod sursa (job #3038377)
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream cin("fmcm.in");
ofstream cout("fmcm.out");
const int MAX = 351;
const int inf = 1e9 + 1;
int f[MAX][MAX] , cap[MAX][MAX] , n , m , source , sink , x , y , z , c , pre[MAX] , dist[MAX];
bool in_q[MAX];
struct muchie{
int y , c;
};
vector <muchie> g[MAX];
bool bf(){
for(int i = 1 ; i <= n ; i++){
pre[i] = 0;
dist[i] = inf;
}
dist[source] = 0;
queue <int> q;
q.push(source);
while(!q.empty()){
x = q.front();
in_q[x] = 0;
q.pop();
for(auto it : g[x]){
if(cap[x][it.y] - f[x][it.y] > 0 && dist[it.y] > dist[x] + it.c){
pre[it.y] = x;
dist[it.y] = dist[x] + it.c;
if(!in_q[it.y]){
q.push(it.y);
in_q[it.y] = 1;
}
}
}
}
if(dist[sink] == inf) return 0;
return 1;
}
int main(){
cin >> n >> m >> source >> sink;
while(m--){
cin >> x >> y >> c >> z;
g[x].push_back({y,z});
g[y].push_back({x,-z});
cap[x][y] = c;
}
int sum_cost = 0, new_flow , aux , new_val;
while(bf()){
new_val = dist[sink];
new_flow = inf;
aux = sink;
while(pre[sink]){
new_flow = min(new_flow,cap[pre[sink]][sink] - f[pre[sink]][sink]);
sink = pre[sink];
}
sink = aux;
while(pre[sink]){
f[pre[sink]][sink] += new_flow;
f[sink][pre[sink]] -= new_flow;
sink = pre[sink];
}
sink = aux;
sum_cost += new_flow*new_val;
}
cout << sum_cost;
return 0;
}