import sys input = sys.stdin.readline def read_values(): return tuple(map(int, input().split())) def read_list(): return list(map(int, input().split())) import heapq class mcf_graph(): n=1 pos=[] g=[[]] def __init__(self,N): self.n=N self.pos=[] self.g=[[] for i in range(N)] def add_edge(self,From,To,cap,cost): assert 0<=From and From= 0 for all edge ''' dual=[0 for i in range(self.n)] dist=[0 for i in range(self.n)] pv=[0 for i in range(self.n)] pe=[0 for i in range(self.n)] vis=[False for i in range(self.n)] def dual_ref(): for i in range(self.n): dist[i]=-1-(-1<<63) pv[i]=-1 pe[i]=-1 vis[i]=False que=[] heapq.heappush(que,(0,s)) dist[s]=0 while(que): v=heapq.heappop(que)[1] if vis[v]:continue vis[v]=True if v==t:break ''' dist[v] = shortest(s, v) + dual[s] - dual[v] dist[v] >= 0 (all reduced cost are positive) dist[v] <= (n-1)C ''' for i in range(len(self.g[v])): e=self.g[v][i] if vis[e[0]] or (not(e[2])):continue ''' |-dual[e.to]+dual[v]| <= (n-1)C cost <= C - -(n-1)C + 0 = nC ''' cost=e[3]-dual[e[0]]+dual[v] if dist[e[0]]-dist[v]>cost: dist[e[0]]=dist[v]+cost pv[e[0]]=v pe[e[0]]=i heapq.heappush(que,(dist[e[0]],e[0])) if not(vis[t]): return False for v in range(self.n): if not(vis[v]):continue dual[v]-=dist[t]-dist[v] return True flow=0 cost=0 prev_cost=-1 result=[(flow,cost)] while(flow