Pagini recente » Cod sursa (job #2042140) | Cod sursa (job #2839379)
#include <bits/stdc++.h>
//#pragma GCC optimize ("03")
#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 ll long long
#define ull unsigned long long
#define ld long double
#define eb emplace_back
#define pb push_back
#define qwerty1 first
#define qwerty2 second
#define qwerty3 -> first
#define qwerty4 -> second
#define umap unordered_map
#define uset unordered_set
#define pii pair < int , int >
#define dbg(x) cerr << #x << ": " << x << '\n'
namespace FastRead
{
char __buff[5000];int __lg = 0 , __p = 0;
char nc()
{
if(__lg == __p){__lg = fread(__buff , 1 , 5000 , stdin);__p = 0;if(!__lg) return EOF;}
return __buff[__p++];
}
template<class T>void read(T&__x)
{
T __sgn = 1; char __c;while(!isdigit(__c = nc()))if(__c == '-')__sgn = -1;
__x = __c - '0';while(isdigit(__c = nc()))__x = __x * 10 + __c - '0';__x *= __sgn;
}
}
using namespace FastRead;
using namespace std;
const int N = 355;
const int M = 1e9 + 7;
const ld PI = acos(-1);
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
int n , m , x , y , c , z , sink , source;
vector < int > G[N];
int cost[N][N] , capacity[N][N] , dist[N] , d[N] , parent[N];
bool inq[N];
queue < int > q;
priority_queue < pii , vector < pii > , greater < pii > > pq;
void bellman()
{
for(int i = 1 ; i <= n ; i++)
dist[i] = INT_MAX;
dist[source] = 0;
q.push(source);
inq[source] = 1;
while(!q.empty())
{
int node = q.front(); q.pop();
inq[node] = 0;
for(auto i : G[node])
if(capacity[node][i] && dist[node] + cost[node][i] < dist[i])
{
dist[i] = dist[node] + cost[node][i];
if(!inq[i]) q.push(i);
inq[i] = 1;
}
}
}
bool djikstra()
{
for(int i = 1 ; i <= n ; i++)
d[i] = INT_MAX , parent[i] = 0;
d[source] = 0;
pq.push({0 , source});
while(!pq.empty())
{
int node = pq.top().second;
int curr_dist = pq.top().first;
pq.pop();
if(d[node] != curr_dist) continue;
for(auto to : G[node])
if(capacity[node][to] && d[node] + (dist[node] + cost[node][to] - dist[to]) < d[to])
{
d[to] = d[node] + (dist[node] + cost[node][to] - dist[to]);
parent[to] = node;
pq.push({d[to] , to});
}
}
return d[sink] != INT_MAX;
}
int Flow()
{
int flow = 0;
int mnCost = 0;
while(djikstra())
{
int mnFlow = INT_MAX;
for(int curr = sink ; curr != source ; curr = parent[curr])
mnFlow = min(mnFlow , capacity[parent[curr]][curr]);
flow += mnFlow;
for(int curr = sink ; curr != source ; curr = parent[curr])
{
capacity[parent[curr]][curr] -= mnFlow;
capacity[curr][parent[curr]] += mnFlow;
mnCost += mnFlow * cost[parent[curr]][curr];
}
}
return mnCost;
}
signed main()
{
#ifndef ONLINE_JUDGE
FastIO , FILES;
#endif
read(n) , read(m) , read(source) , read(sink);
while(m--)
{
read(x) , read(y) , read(c) , read(z);
G[x].pb(y);
G[y].pb(x);
capacity[x][y] = c;
capacity[y][x] = 0;
cost[x][y] = z;
cost[y][x] = -z;
}
bellman();
cout << Flow();
return 0;
}