Pagini recente » Cod sursa (job #1252334) | Cod sursa (job #2984112) | Cod sursa (job #1252441) | Cod sursa (job #1252337) | Cod sursa (job #3217555)
#include<bits/stdc++.h>
#define FastIO ios_base::sync_with_stdio(false) , cin.tie(0) , cout.tie(0)
#define FILES freopen("fmcm.in" , "r" , stdin) , freopen("fmcm.out" , "w" , stdout)
#define pii pair < int , int >
#define pb push_back
using namespace std;
const int N = 355;
struct FMCM
{
#define N 1005
int n , source , sink;
int capacity[N][N] , weight[N][N] , parent[N];
int d[N] , nd[N];
vector < int > G[N];
priority_queue < int , vector < pii > , greater < pii > > s;
queue < int > q;
bitset < N > inq;
inline void bellman()
{
int i;
for(i = 1 ; i <= n ; i++)
d[i] = INT_MAX;
d[source] = 0;
q.push(source);
while(!q.empty())
{
int u = q.front();
q.pop();
inq[u] = 0;
for(auto v : G[u])
{
if(capacity[u][v] && d[v] > d[u] + weight[u][v])
{
d[v] = d[u] + weight[u][v];
if(inq[v])
continue;
inq[v] = 1;
q.push(v);
}
}
}
}
int k = INT_MAX;
int flow = 0;
int minCost = 0;
bool inline djikstra()
{
int i;
for(i = 1 ; i <= n ; i++)
nd[i] = INT_MAX;
nd[source] = 0;
s.push({0 , source});
while(!s.empty())
{
int u = s.top().second;
int cst = s.top().first;
s.pop();
if(nd[u] != cst)
continue;
for(auto v : G[u])
{
if(capacity[u][v])
{
if(nd[v] > nd[u] + weight[u][v] + d[u] - d[v])
{
parent[v] = u;
nd[v] = nd[u] + weight[u][v] + d[u] - d[v];
s.push({nd[v] , v});
}
}
}
}
if(nd[sink] == INT_MAX)
return 0;
int minFlow = k - flow;
int curr;
int sumCost = 0;
for(curr = sink ; curr != source ; curr = parent[curr])
minFlow = min(minFlow , capacity[parent[curr]][curr]);
for(curr = sink ; curr != source ; curr = parent[curr])
{
capacity[parent[curr]][curr] -= minFlow;
capacity[curr][parent[curr]] += minFlow;
sumCost += weight[parent[curr]][curr];
}
flow += minFlow;
minCost += sumCost * minFlow;
return 1;
}
void addEdge(int x , int y , int c , int z)
{
capacity[x][y] = c;
weight[x][y] = z;
weight[y][x] = -z;
G[x].pb(y);
G[y].pb(x);
}
int F()
{
bellman();
for( ; djikstra() ; );
return minCost;
}
}F;
signed main()
{
#ifndef ONLINE_JUDGE
FastIO , FILES;
#endif
int n , m , source , sink;
cin >> n >> m >> source >> sink;
F.source = source;
F.sink = sink;
while(m--)
{
int x , y , c , z;
cin >> x >> y >> c >> z;
F.addEdge(x , y , c , z);
}
cout << F.F();
return 0;
}