Pagini recente » Cod sursa (job #1287200) | Cod sursa (job #2986877) | Cod sursa (job #2877558) | Cod sursa (job #2833704) | Cod sursa (job #2965162)
#include <bits/stdc++.h>
//#pragma GCC optimize("Ofast")
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];
int d[Max];
int p[Max];
bitset < Max > inq;
const int INF = 1e9;
void Shortest_paths(int n, int v0)
{
//bellman ford
int i;
for(i=1;i<=n;i++)
d[i] = INF,p[i] = -1;
d[v0] = 0;
inq.reset();
queue < int > q;
q.push(v0);
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;
while(true)
{
//cout<<"actualizez un picut \n";
Shortest_paths(n + 1,s);
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;
}