Cod sursa(job #2631131)

Utilizator Leonard123Mirt Leonard Leonard123 Data 29 iunie 2020 09:22:23
Problema Flux maxim de cost minim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.33 kb
#include<bits/stdc++.h>
#define pb push_back
#define ft first
#define maxn 355
#define sd second
#define inf 0x3f3f3f3f
using namespace std;
vector<int>v[maxn];
queue<int>q;
pair<int,int> c[maxn][maxn];
int f[maxn][maxn],cost[maxn],viz[maxn],tt[maxn],n,m,d,s,flux,Cost;

void solve(){
        while(cost[d]!=inf){
                q.push(s);
                memset(cost, inf, sizeof(cost));
                memset(viz, 0, sizeof(viz));
                viz[s]=1;cost[s]=0;
                while(!q.empty()){
                        int nod=q.front();
                        q.pop();
                        viz[nod]=0;
                        if(nod==d)
                                continue;
                        for(int i=0; i<v[nod].size(); i++){
                                int dest=v[nod][i];
                                if(cost[nod]+c[nod][dest].sd>=cost[dest]||f[nod][dest]==c[nod][dest].ft)
                                        continue;
                                if(cost[nod]+c[nod][dest].sd<cost[dest]){
                                        cost[dest]=cost[nod]+c[nod][dest].sd;
                                        tt[dest]=nod;
                                        if(viz[dest]==0)viz[dest]=1,q.push(dest);
                                }
                        }
                }
                if(cost[d]!=inf){
                                flux=inf;
                                if(cost[tt[d]]==inf || c[tt[d]][d].ft==f[tt[d]][d])
                                        continue;
                                for(int wh=d; wh!=s; wh=tt[wh])
                                        flux=min(flux, c[tt[wh]][wh].ft-f[tt[wh]][wh]);
                                for(int wh=d; wh!=s; wh=tt[wh])
                                        f[tt[wh]][wh]+=flux,
                                        f[wh][tt[wh]]-=flux;
                                Cost+=flux*cost[d];
                        }
        }
        cout<<Cost;
}


int main(){
        freopen("fmcm.in","r",stdin);
        freopen("fmcm.out", "w", stdout);
        ios_base::sync_with_stdio(0);
        cin.tie(0);
        cin>>n>>m>>s>>d;
        int x,y,z,w;
        while(m--){
                cin>>x>>y>>w>>z;
                v[x].pb(y); v[y].pb(x);
                c[x][y].ft=w; c[x][y].sd=z; c[y][x].sd=-z;
        }
        solve();
        return 0;
}