#include using namespace std; //Minimum Cost Flow O(FE log V) #include #include #include #include #include template struct MCF{ struct edge{ int to,rev,cap; T cost; }; vector >G; vectorh,d; vectorpv,pe; MCF(int n_=0):G(n_),h(n_,0),d(n_),pv(n_),pe(n_){} void add_edge(int from,int to,int cap,T cost) { G[from].push_back({to,(int)G[to].size(),cap,cost}); G[to].push_back({from,(int)G[from].size()-1,0,-cost}); } T min_cost_flow(int s,int t,int f)//ans or -1 { T ret=0; bool fst=true; while(f>0) { fill(d.begin(),d.end(),numeric_limits::max()); d[s]=0; if(fst) { fst=false; while(true) { bool ch=false; for(int i=0;i::max()) { for(int j=0;j0&&d[e.to]>d[i]+e.cost) { d[e.to]=d[i]+e.cost; pv[e.to]=i; pe[e.to]=j; ch=true; } } } if(!ch)break; } } else { priority_queue,vector >,greater > >P; P.push(make_pair(0,s)); while(!P.empty()) { pairp=P.top();P.pop(); if(d[p.second]0&&d[e.to]>d[p.second]+e.cost+h[p.second]-h[e.to]) { d[e.to]=d[p.second]+e.cost+h[p.second]-h[e.to]; pv[e.to]=p.second; pe[e.to]=i; P.push(make_pair(d[e.to],e.to)); } } } } if(d[t]==numeric_limits::max())return -1; for(int u=0;u>N>>K; for(int i=0;i>A[i]; for(int i=0;i>B[i]; for(int i=0;i>P[i][j]; ans+=P[i][j]*P[i][j]; } MCFQ(N*N+2*N+2); int st=N*N+2*N,go=st+1; for(int i=0;i