Cod sursa(job #2642716)

Utilizator MoldovanAndrei1Moldovan Andrei MoldovanAndrei1 Data 16 august 2020 20:44:46
Problema Flux maxim de cost minim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.62 kb
#include <bits/stdc++.h>
using namespace std;
const int NMAX  = 355;
struct edge
{
    int from , to , flow , cost;
};
int n , s ,t;
vector <int> adia[NMAX];
int cap[NMAX][NMAX] , p[NMAX] , d[NMAX] , cost[NMAX][NMAX],viz[NMAX];
bool bellman()
{
  for(int i = 1 ; i <= n ;++i)p[i] = -1 , viz[i] = 0 , d[i] = 1e9;
  queue <int> q;
  q.push(s);
  d[s] = 0 ;
  viz[s] = 1;
  while(!q.empty())
  {
      int nod = q.front();
      q.pop();
      viz[nod] = 0;
      for(int i : adia[nod])
      {
          if(cap[nod][i] <= 0)continue;
          if(d[i] > d[nod] + cost[nod][i])
          {
              d[i] = d[nod] + cost[nod][i];
              if(!viz[i])
                q.push(i),viz[i] = 1;
              p[i] = nod;
          }
      }
  }
  return d[t]!=1e9;
}
int get_flow()
{
    int t1  =t , f= 1e9;
    for(;t1!=s;t1=p[t1])
        f=min(f,cap[p[t1]][t1]);
    return f;
}
int update(int flux)
{
    int t1 = t;
    for(;t1!=s ; t1= p[t1])
    {
        cap[p[t1]][t1]-=flux;
        cap[t1][p[t1]]+=flux;
    }
    return flux * d[t];
}
int min_cost_flow()
{
    int cost = 0;
    while(bellman())
    cost+=update(get_flow());
    return cost;
}
int main()
{
    freopen("fmcm.in","r",stdin);
    freopen("fmcm.out","w",stdout);
    int m,s1,d1;
    cin>>n>>m>>s>>t;
    for(int i=1;i<=m;i++)
    {
        int a,b,c,d;
        cin>>a>>b>>c>>d;
        cap[a][b] = c;
        cap[b][a] = 0;
        cost[a][b] = d;
        cost[b][a] = -d;
        adia[a].push_back(b);
        adia[b].push_back(a);
    }
    int res=min_cost_flow();
    cout<<res;
    return 0;
}