defhgr(g):# g 是二分图中每个 x 对应的 y 列表deffind(x):forying[x]:ifynotinvis:vis.add(y)ifynotindorfind(d[y]):d[y]=xreturnTruereturnFalseres,vis,d=0,set(),{}forxing:res+=find(x)vis.clear()returnres
defkm(g):# g 是 n-n 完全二分图的权值defbfs(i):slack=[inf]*nvis=[0]*(n+1)pre=[-1]*nj=nj=-1d[j]=iwhiled[j]!=-1:delta=infx=d[j]vis[j]=Trueforyinrange(n):ifvis[y]:continuetmp=lx[x]+ly[y]-g[x][y]ifslack[y]>tmp:slack[y]=tmppre[y]=jifslack[y]<delta:delta=slack[y]nj=ylx[i]-=deltaforyinrange(n):ifvis[y]:lx[d[y]]-=deltaly[y]+=deltaelse:slack[y]-=deltaj=njwhilej!=-1:d[j]=d[pre[j]]j=pre[j]n=len(g)d=[-1]*(n+1)lx=[max(row)forrowing]ly=[0]*nforiinrange(n):bfs(i)returnsum(g[d[y]][y]foryinrange(n))