Pagini recente » Cod sursa (job #2334802) | Cod sursa (job #2344771) | Cod sursa (job #1225570) | Cod sursa (job #1024542) | Cod sursa (job #3032099)
#include <fstream>
#include <cstring>
#include <vector>
#include <deque>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <algorithm>
#include <iomanip>
#include <cmath>
#include <cstdlib>
#include <ctime>
using namespace std;
ifstream cin("fmcm.in");
ofstream cout("fmcm.out");
using ll = long long;
//#define int ll
using pi = pair<int,int>;
using pll = pair<ll, ll>;
#define pb push_back
#define x first
#define y second
struct vertex
{
ll cost, u;
bool operator <(const vertex &oth) const
{
return cost > oth.cost;
}
};
struct edge
{
ll a, b, c, w;
};
const int MOD = 1e9+7, INF = 1e9, NMAX = 355;
int cap[NMAX][NMAX], d[NMAX], p[NMAX], dist[NMAX], n, act[NMAX], cost[NMAX][NMAX];
vector<pi> v[NMAX], adj[NMAX];
vector<edge> E;
void bellmanford(int src)
{
int i, u, nod, w;
queue<int> q;
for(i = 1; i <= n; i++)
d[i] = INF;
d[src] = 0;
q.push(src);
act[src] = 1;
while(!q.empty())
{
u = q.front();
q.pop();
act[u] = 0;
for(i = 0; i < adj[u].size(); i++)
{
nod = adj[u][i].x;
w = adj[u][i].y;
if(d[nod] > d[u] + w)
{
d[nod] = d[u] + w;
if(!act[nod])
{
act[nod] = 1;
q.push(nod);
}
}
}
}
}
int dijkstra(int src, int dest)
{
int i, nod, w;
vertex u;
for(i = 1; i <= n; i++)
{
dist[i] = INF;
p[i] = 0;
}
multiset<vertex> pq;
dist[src] = 0;
p[src] = src;
pq.insert({0, src});
while(!pq.empty())
{
u = *pq.begin();
pq.erase(pq.begin());
if(u.cost > dist[u.u])
continue;
for(i = 0; i < v[u.u].size(); i++)
{
nod = v[u.u][i].x;
w = v[u.u][i].y;
if(dist[nod] > u.cost + w + d[u.u] - d[nod] && cap[u.u][nod] > 0)
{
dist[nod] = u.cost + w + d[u.u] - d[nod];
p[nod] = u.u;
pq.insert({dist[nod], nod});
}
}
}
return dist[dest] != INF;
}
void solve()
{
int m, i, j, src, dest, a, b, c, w, new_cost, flow, new_flow, u, ans;
edge e;
cin >> n >> m >> src >> dest;
for(i = 0; i < m; i++)
{
cin >> a >> b >> c >> w;
cost[a][b] = w;
cost[b][a] = -w;
E.pb({a, b, c, w});
adj[a].pb({b, w});
}
bellmanford(src);
for(i = 0; i < m; i++)
{
e = E[i];
cap[e.a][e.b] = e.c;
new_cost = e.w /*+ d[e.a] - d[e.b]*/;
v[e.a].pb({e.b, new_cost});
v[e.b].pb({e.a, -new_cost});
}
flow = 0;
while(dijkstra(src, dest))
{
new_flow = INF;
u = dest;
ans = 0;
while(u != src)
{
ans += cost[p[u]][u];
new_flow = min(new_flow, cap[p[u]][u]);
u = p[u];
}
u = dest;
while(u != src)
{
cap[p[u]][u] -= new_flow;
cap[u][p[u]] += new_flow;
u = p[u];
}
flow = flow + new_flow * ans;
}
cout << flow;
}
int main()
{
cin.tie(0)->sync_with_stdio(0);
cin.exceptions(cin.failbit);
int T;
T = 1;
while(T--)
solve();
return 0;
}