import sys read=sys.stdin.buffer.read readline=sys.stdin.buffer.readline readlines=sys.stdin.buffer.readlines import heapq class MinCostFlow: def __init__(self, n, neg=False): self.n=n self.g=[[] for _ in range(n)] self.h=[0]*n self.neg=neg def add_edge(self, frm, to, cap, cost): g=self.g g[frm].append([to, cap, cost, len(g[to])]) g[to].append([frm, 0, -cost, len(g[frm])-1]) def bellman_ford(self, s, prevv, preve): n=self.n g=self.g h=self.h INF=10**18 for x in range(n): h[x]=INF h[s]=0 for _ in range(n-1): for x in range(n): for i, e in enumerate(g[x]): if e[1]==0: continue to, cost=e[0], e[2] if h[to]>h[x]+cost: h[to]=h[x]+cost prevv[to]=x preve[to]=i def flow(self, s, t, f): res=0 n=self.n g=self.g h=self.h INF=10**16 LOG=16 #n<2**LOG prevv=[0]*n preve=[0]*n while f>0: if self.neg: self.neg=False self.bellman_ford(s, prevv, preve) if h[t]==INF: return -1 else: que=[] dist=[INF]*n dist[s]=0 heapq.heappush(que, s) while que: p=heapq.heappop(que) v=(p&((1<>LOG): continue for i, e in enumerate(g[v]): if e[1]==0: continue to, cost=e[0], e[2] if dist[to]>dist[v]+cost+h[v]-h[to]: dist[to]=dist[v]+cost+h[v]-h[to] prevv[to]=v preve[to]=i heapq.heappush(que, (dist[to]<