Pagini recente » Cod sursa (job #2633761) | Cod sursa (job #52280) | Cod sursa (job #562808) | Cod sursa (job #2195909) | Cod sursa (job #3032146)
#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 ll MOD = 1e9+7, INF = 1e18, NMAX = 355;
ll cap[NMAX][NMAX], d[NMAX], p[NMAX], dist[NMAX], n, act[NMAX], cost[NMAX][NMAX], costw[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 && cap[u][nod] > 0)
{
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;
costw[i] = INF;
}
priority_queue <vertex> pq;
dist[src] = 0;
costw[src] = 0;
p[src] = src;
pq.push({0, src});
while(!pq.empty())
{
u = pq.top();
pq.pop();
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];
costw[nod] = costw[u.u] + w;
p[nod] = u.u;
pq.push({dist[nod], nod});
}
}
}
return dist[dest] != INF;
}
void solve()
{
ll 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;
cap[a][b] = c;
v[a].pb({b, w});
v[b].pb({a, -w});
}
bellmanford(src);
flow = 0;
while(dijkstra(src, dest))
{
new_flow = INF;
u = dest;
while(u != src)
{
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 * costw[dest];
}
cout << flow;
}
int main()
{
cin.tie(0)->sync_with_stdio(0);
cin.exceptions(cin.failbit);
int T;
T = 1;
while(T--)
solve();
return 0;
}