struct node
{
ll to,flow,cost,rev;
};
ll now[MAXN],dep[MAXN];
bool vis[MAXN];
vector<node>ed[MAXN];
bool bfs(ll n,ll s,ll t)
{
for(int i=1;i<=n;i++)
{
now[i]=0;
dep[i]=inf;
}
queue<ll>g;
g.push(s);
dep[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(dep[to]>dep[u]+cost&&flow)
{
dep[to]=dep[u]+cost;
if(!vis[to])
{
vis[to]=1;
g.push(to);
}
}
}
}
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=0;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==dep[to]&&!vis[to])
{
pair<ll,ll> tt=dfs(to,min(x,flow),t);
ll ttt=tt.first;
if(!ttt)dep[to]=0;
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};
while(bfs(n,s,t))
{
pair<ll,ll> tt=dfs(s,inf,t);
ans={ans.first+tt.first,ans.second+tt.second};
}
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});
}费用流
这是 2026年4月29日 存档的第 1 版,不是当前版本。查看当前版本