洛谷-P3381 【模板】最小费用最大流
作者:互联网
【模板】最小费用最大流
EK 改 SPFA
#include <iostream>
#include <queue>
#include <algorithm>
using namespace std;
typedef long long ll;
const int maxn = 1e5 + 10;
const ll inf = 1e17 + 10;
int tp = 1, nex[maxn], head[maxn], to[maxn], vis[maxn], last[maxn];
ll cost[maxn], dis[maxn], val[maxn], flow[maxn];
int n, m, s, t;
void add(int u, int v, ll f, ll c)
{
tp++;
nex[tp] = head[u];
head[u] = tp;
to[tp] = v;
cost[tp] = c;
val[tp] = f;
}
ll SPFA()
{
for(int i=0; i<=n; i++) flow[i] = last[i] = 0;
for(int i=0; i<=n; i++) dis[i] = inf;
dis[s] = 0;
queue<int>q;
q.push(s);
flow[s] = inf;
while(!q.empty())
{
int now = q.front();
q.pop();
vis[now] = 0;
for(int i=head[now]; i; i=nex[i])
{
int v = to[i];
if(val[i] > 0 && dis[now] + cost[i] < dis[v])
{
dis[v] = dis[now] + cost[i];
flow[v] = min(flow[now], val[i]);
last[v] = i ^ 1;
if(vis[v] == 0)
{
vis[v] = 1;
q.push(v);
}
}
}
}
return flow[t];
}
ll ans = 0, cur = 0;
void EK()
{
ans = cur = 0;
while(SPFA())
{
ans += flow[t];
for(int i=last[t]; i; i=last[to[i]])
{
cur += cost[i ^ 1] * flow[t];
val[i] += flow[t];
val[i ^ 1] -= flow[t];
}
}
}
int main()
{
cin >> n >> m >> s >> t;
while(m--)
{
int u, v;
ll f, c;
cin >> u >> v >> f >> c;
add(u, v, f, c);
add(v, u, 0, -c);
}
EK();
cout << ans << " " << cur << endl;
return 0;
}
Dinic 里的 bfs 分层改成 SPFA 分层
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
using namespace std;
typedef long long ll;
const int maxn = 1e5 + 10;
const ll inf = 1e17 + 10;
int n, m, s, t, tp = 1;
int head[maxn], nex[maxn], to[maxn], cur[maxn], vis[maxn];
ll val[maxn], cost[maxn], dis[maxn];
void add(int u, int v, ll f, ll c)
{
tp++;
nex[tp] = head[u];
head[u] = tp;
to[tp] = v;
cost[tp] = c;
val[tp] = f;
}
bool spfa()
{
for(int i=0; i<=n; i++) cur[i] = head[i];
for(int i=0; i<=n; i++) dis[i] = inf;
dis[s] = 0;
queue<int>q;
q.push(s);
while(q.size())
{
int u = q.front();
q.pop();
vis[u] = 0;
for(int i=head[u]; i; i=nex[i])
{
int v = to[i];
if(val[i] > 0 && dis[u] + cost[i] < dis[v])
{
dis[v] = dis[u] + cost[i];
if(vis[v] == 0)
{
vis[v] = 1;
q.push(v);
}
}
}
}
return dis[t] != inf;
}
ll c_ans = 0;
ll dfs(int now, ll flow)
{
if(now == t) return flow;
vis[now] = 1;
ll ans = 0;
for(int i=cur[now]; i && ans < flow; i=nex[i])
{
cur[now] = i;
int v = to[i];
if(vis[v] == 0 && val[i] > 0 && dis[v] == dis[now] + cost[i])
{
ll x = dfs(v, min(val[i], flow - ans));
c_ans += x * cost[i];
val[i] -= x;
val[i ^ 1] += x;
ans += x;
}
}
vis[now] = 0;
return ans;
}
ll mcmf()
{
ll ans = 0;
while(spfa())
{
ll x = dfs(s, inf);
ans += x;
}
return ans;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n >> m >> s >> t;
while(m--)
{
int u, v;
ll f, c;
cin >> u >> v >> f >> c;
add(u, v, f, c);
add(v, u, 0, -c);
}
ll ans = mcmf();
cout << ans << " " << c_ans << endl;
return 0;
}
标签:洛谷,val,int,ll,tp,maxn,P3381,ans,模板 来源: https://www.cnblogs.com/dgsvygd/p/16365034.html