lightoj 1198 最大权重匹配
题目链接:http://lightoj.com/volume_showproblem.php?problem=1198
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include <cstdio> #include <cstring> #include <cmath> #include <iostream> #include <algorithm> #include <queue> #include <vector> using namespace std; const int maxn = 150; const int maxe = 5000; const int INF = 0x3f3f3f; struct Edge{ int u,v,flow,cap,cost; int next; Edge(int u=0,int v=0,int flow=0,int cap=0,int cost=0,int next=0): u(u), v(v), flow(flow), cap(cap), cost(cost), next(next) {} }; struct MCMF{ Edge edges[maxe]; int head[maxn],cnt; int d[maxn]; bool inq[maxn]; int pa[maxn]; int res[maxn]; void init(){ memset(head,-1,sizeof(head)); cnt = 0; } void addedge(int u,int v,int cap,int cost){ edges[cnt] = Edge(u,v,0,cap,cost,head[u]); head[u] = cnt++; edges[cnt] = Edge(v,u,0,0,-cost,head[v]); head[v] = cnt++; } bool SPFA(int s,int t,int& flow,int& cost){ memset(inq,0,sizeof(inq)); memset(d,-0x3f,sizeof(d)); queue<int> Q; Q.push(s); inq[s] = true; d[s] = 0; pa[s] = s; res[s] = INF; res[t] = 0; while(!Q.empty()){ int u = Q.front(); Q.pop(); inq[u] = false; for(int i=head[u];i!=-1;i=edges[i].next){ Edge& e = edges[i]; if(e.cap>e.flow && d[e.v] < d[u] + e.cost){ d[e.v] = d[u] + e.cost; res[e.v] = min(res[u],e.cap-e.flow); pa[e.v] = i; if(!inq[e.v]){ inq[e.v] = true; Q.push(e.v); } } } } if(!res[t]) return false; flow += res[t]; cost += res[t]*d[t]; for(int i=t;i!=s;i=edges[pa[i]].u){ edges[pa[i]].flow += res[t]; edges[pa[i]^1].flow -= res[t]; } return true; } int MaxCost(int s,int t){ int flow = 0, cost = 0; while(SPFA(s,t,flow,cost)); printf("%d\n",cost); } }solver; int main() { //freopen("E:\\acm\\input.txt","r",stdin); int T; cin>>T; for(int cas=1;cas<=T;cas++){ solver.init(); int N; cin>>N; int A[maxn],B[maxn]; int s = 0, t = 2*N+1; for(int i=1;i<=N;i++) scanf("%d",&A[i]),solver.addedge(s,i,1,0); for(int i=1;i<=N;i++) scanf("%d",&B[i]),solver.addedge(i+N,t,1,0); for(int i=1;i<=N;i++) for(int j=1;j<=N;j++){ if(A[i] > B[j]) solver.addedge(i,j+N,1,2); else if(A[i] == B[j]) solver.addedge(i,j+N,1,1); else solver.addedge(i,j+N,1,0); } printf("Case %d: ",cas); solver.MaxCost(s,t); } }