Cod sursa(job #2631086)

Utilizator Leonard123Mirt Leonard Leonard123 Data 28 iunie 2020 19:45:37
Problema Flux maxim de cost minim Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.45 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(){
	viz[d]=1;
	while(viz[d]){
		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();
			if(nod==n)
				continue;
			for(int i=0; i<v[nod].size(); i++){
				int dest=v[nod][i];
				if(viz[dest]||f[nod][dest]==c[nod][dest].ft)
					continue;
				if(cost[nod]+c[nod][dest].sd<cost[dest]){
					q.push(dest);
					cost[dest]=cost[nod]+c[nod][dest].sd;
					tt[dest]=nod;
					viz[dest]=1;
				}
			}
		}
		if(viz[d]){
			for(int i=0; i<=v[d].size(); i++){
				flux=inf;
				int nod=v[d][i];
				if(!viz[nod] || c[nod][d].ft==f[nod][d])
					continue;
				tt[d]=nod;
				for(int wh=d; wh!=s; wh=tt[wh])
					flux=min(flux, c[tt[wh]][wh].ft-f[tt[wh]][wh]);
				if(flux==0) continue;
				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;
}