Nu aveti permisiuni pentru a descarca fisierul arbint2-update.png
Cod sursa(job #2781000)
Utilizator | Data | 8 octombrie 2021 11:40:38 | |
---|---|---|---|
Problema | Flux maxim de cost minim | Scor | 50 |
Compilator | cpp-64 | Status | done |
Runda | Arhiva educationala | Marime | 2.44 kb |
#include <bits/stdc++.h>
using namespace std;
ifstream f("fmcm.in");
ofstream g("fmcm.out");
#define cin f
#define cout g
//#define int long long
const int Max = 351;
void nos()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
}
//https://cp-algorithms.com/graph/min_cost_flow.html
struct Edge{
int from, to ,capacity,cost;};
vector < vector < int > > graph;
int cost[Max][Max];
int capacity[Max][Max];
const int INF = 1e9;
void Shortest_paths(int n, int v0,vector < int >& d, vector < int >&p)
{
//bellman ford
d.assign(n ,INF);
d[v0] = 0;
vector < bool > inq(n,false);
queue < int > q;
q.push(v0);
p.assign(n ,-1);
while(!q.empty())
{
int nod = q.front();
q.pop();
inq[nod] = false;
for(auto vec : graph[nod])
if(capacity[nod][vec] > 0 and d[vec] > d[nod] + cost[nod][vec])
{
d[vec] = d[nod] + cost[nod][vec];
p[vec] = nod;
if(!inq[vec])
{
inq[vec] = true;
q.push(vec);
}
}
}
}
pair < int , int > MCMF_cost(int n,vector < Edge > edges,int s, int t)
{
graph.assign(n + 1,vector<int>());
for(auto e : edges)
{
graph[e.from].push_back(e.to);
graph[e.to].push_back(e.from);
cost[e.from][e.to] = e.cost;
cost[e.to][e.from] = -e.cost;
capacity[e.from][e.to] = e.capacity;
}
int flow = 0;
int cost = 0;
vector < int > d,p;
while(true)
{
//cout<<"actualizez un picut \n";
Shortest_paths(n + 1,s,d,p);
if(d[t] == INF)
break;
int thisflow = INF;
int current = t;
while(current != s)
{
thisflow = min(thisflow,capacity[p[current]][current]);
current = p[current];
}
//am cam terminat
flow += thisflow;
cost += thisflow * d[t];
current = t;
while(current != s)
{
capacity[p[current]][current] -= thisflow;
capacity[current][p[current]] += thisflow;
current = p[current];
}
//actualizez muchiile alese
}
return {flow,cost};
}
int n,m,source,sink;
vector < Edge > muchii;
void read()
{
f>>n>>m>>source>>sink;
int i;
for(i=1;i<=m;i++)
{
int from,to,cap,cost;
f>>from>>to>>cap>>cost;
muchii.push_back({from,to,cap,cost});
}
}
void solve()
{
//MCMF flow_graph;
cout<<MCMF_cost(n,muchii,source,sink).second;
}
void restart()
{
}
int32_t main()
{
//nos();
read();
solve();
restart();
return 0;
}