18 MinCostFlow(
int n) { graph.resize(n),dist.resize(n),pot.resize(n),pv.resize(n),pe.resize(n); }
22 void add_edge(
int from,
int to, ll cap, ll cost) {
23 graph[from].push_back(Edge(from,to,cap,cost,graph[to].size(),
false));
24 graph[to].push_back(Edge(to,from,0,-cost,(
int)graph[from].size()-1,
true));
39 ll
flow(
int s,
int t, ll f) {
41 rpriority_queue<pair<ll,
int>> pq;
42 fill(pot.begin(),pot.end(),0);
43 fill(pv.begin(),pv.end(),0);
44 fill(pe.begin(),pe.end(),0);
48 fill(dist.begin(),dist.end(),INFL);
52 auto [tmp,now]=pq.top();
54 if(dist[now]<tmp)
continue;
55 for(
int i=0; i<graph[now].size(); i++) {
56 auto [from,to,rev,cap,cost,isrev]=graph[now][i];
57 ll ncost=dist[now]+cost+pot[now]-pot[to];
58 if(cap>0&&dist[to]>ncost) {
59 dist[to]=ncost,pv[to]=now,pe[to]=i;
60 pq.push({dist[to],to});
64 if(dist[t]==INFL)
return INFL;
65 for(
int i=0; i<n; i++) pot[i]+=dist[i];
67 for(
int v=t; v!=s; v=pv[v]) d=min(d,graph[pv[v]][pe[v]].cap);
69 for(
int v=t; v!=s; v=pv[v]) {
70 auto &e=graph[pv[v]][pe[v]];
71 e.cap-=d,graph[v][e.rev].cap+=d;