lightoj 1011 最大权重匹配或最大费用流

时间:2023-03-09 00:45:44
lightoj 1011 最大权重匹配或最大费用流

由于暂时不会KM算法,只能用最大费用流来做了。

题目链接:http://lightoj.com/volume_showproblem.php?problem=1011

#include <cstdio>
#include <cstring>
#include <iostream>
#include <cmath>
#include <algorithm>
#include <queue>
#include <vector>
using namespace std; const int maxe = ;
const int maxn = ;
const int INF = 0x3f3f3f; struct Edge{
int u,v,flow,cap,cost;
int next;
Edge(int u=,int v=,int flow=,int cap=,int cost=,int next=):
u(u), v(v), flow(flow), cap(cap), cost(cost), next(next) {}
}; struct MCMF{
int d[maxn];
bool inq[maxn];
Edge edges[maxe];
int head[maxn],cnt;
int pa[maxn]; //用于回溯找增广路。
int res[maxn]; void init(){
memset(head,-,sizeof(head));
cnt = ;
} void addedge(int u,int v,int cap,int cost){
edges[cnt] = Edge(u,v,,cap,cost,head[u]);
head[u] = cnt++;
edges[cnt] = Edge(v,u,,,-cost,head[v]);
head[v] = cnt++;
} bool SPFA(int s,int t,int& flow,int& cost){
memset(inq,,sizeof(inq));
memset(d,-0x3f,sizeof(d));
queue<int> Q;
Q.push(s);
d[s] = ; inq[s] = true;
res[s] = INF; res[t] = ;
while(!Q.empty()){
int u = Q.front(); Q.pop();
inq[u] = false;
for(int i=head[u];i!=-;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;
pa[e.v] = i;
res[e.v] = min(res[u],e.cap-e.flow);
if(!inq[e.v]){
Q.push(e.v); inq[e.v] = true;
}
}
} }
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]^].flow -= res[t];
}
return true;
} void MaxCost(int s,int t){
int flow = ,cost = ;
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=;cas<=T;cas++){
solver.init();
int N;
cin>>N;
int s = , t = *N + ;
for(int i=;i<=N;i++){
solver.addedge(s,i,,);
solver.addedge(i+N,t,,);
}
for(int i=;i<=N;i++)
for(int j=;j<=N;j++){
int a;
scanf("%d",&a);
solver.addedge(i,j+N,,a);
}
printf("Case %d: ",cas);
solver.MaxCost(s,t);
}
}