费用流
ysy11
·
·
个人记录
struct node
{
ll to,flow,cost,rev;
};
ll now[MAXN],dep[MAXN],h[MAXN];
bool vis[MAXN];
vector<node>ed[MAXN];
void spf(ll n,ll s,ll t)
{
for(int i=1;i<=n;i++)
{
h[i]=inf;
vis[i]=0;
}
queue<ll>g;
g.push(s);
h[s]=0;
while(!g.empty())
{
ll u=g.front();
g.pop();
vis[u]=0;
for(int i=0;i<ed[u].size();i++)
{
ll to=ed[u][i].to;
ll flow=ed[u][i].flow;
ll cost=ed[u][i].cost;
if(h[to]>h[u]+cost&&flow)
{
h[to]=h[u]+cost;
if(!vis[to])
{
vis[to]=1;
g.push(to);
}
}
}
}
}
bool dij(ll n,ll s,ll t)
{
for(int i=1;i<=n;i++)
{
now[i]=0;
dep[i]=inf;
vis[i]=0;
}
priority_queue<pair<ll,ll> >g;
g.push({0,s});
dep[s]=0;
while(!g.empty())
{
ll u=g.top().second;
g.pop();
if(vis[u])continue;
vis[u]=1;
for(int i=0;i<ed[u].size();i++)
{
ll to=ed[u][i].to;
ll flow=ed[u][i].flow;
ll cost=ed[u][i].cost+h[u]-h[to];
if(dep[to]>dep[u]+cost&&flow)
{
dep[to]=dep[u]+cost;
g.push({-dep[to],to});
}
}
}
for(int i=1;i<=n;i++)
{
vis[i]=0;
}
if(dep[t]<inf)return 1;
return 0;
}
pair<ll,ll> dfs(ll u,ll x,ll t)
{
if(u==t)return {x,0};
pair<ll,ll> ans={0ll,0ll};
vis[u]=1;
for(int i=now[u];i<ed[u].size()&&x;i++)
{
now[u]=i;
ll to=ed[u][i].to;
ll flow=ed[u][i].flow;
ll cost=ed[u][i].cost;
if(flow&&dep[u]+cost+h[u]-h[to]==dep[to]&&!vis[to])
{
pair<ll,ll> tt=dfs(to,min(x,flow),t);
ll ttt=tt.first;
if(!ttt)vis[to]=1;
ed[u][i].flow-=ttt;
ed[to][ed[u][i].rev].flow+=ttt;
ans={ans.first+ttt,ans.second+ttt*cost+tt.second};
x-=ttt;
}
}
vis[u]=0;
return ans;
}
pair<ll,ll> dinic(ll n,ll s,ll t)
{
pair<ll,ll> ans={0,0};
spf(n,s,t);
while(dij(n,s,t))
{
pair<ll,ll> tt=dfs(s,inf,t);
ans={ans.first+tt.first,ans.second+tt.second};
for(int i=1;i<=n;i++)
{
h[i]+=dep[i];
}
}
return ans;
}
void add(ll u,ll to,ll flow,ll cost)
{
ed[u].push_back({to,flow,cost,ed[to].size()});
ed[to].push_back({u,0,-cost,ed[u].size()-1});
}