题目大意:曹操带了m个手下去打吕布,吕布有n个手下(n<=m),现在他们决定用手下一对一单挑。给定k个单挑关系,表示吕布的手下VS曹操的手下获得的伤害值,吕布的手下要全部打一次。现在要吕布为手下挑对手,使手下获得的伤害值最小。
题目分析:就是要求一个最小权完备匹配。KM算法解决之。注意建图的时候边权值取相反数,因为KM是求最大权匹配的,求出最大权完备匹配后再取反输出。
关于KM算法,百科讲的还不错,不过还是有点抽象,要详解的话推荐戳这里
图建好了就是跑模版的事了。
详情请见代码:
#include<iostream>
#include<map>
#include<string>
#include<cstring>
#include<cstdio>
using namespace std;
const int N = 205;
const int INF = 0x3f3f3f3f;
int n,m,k,lack;
int w[N][N];
int lx[N],ly[N];
bool sx[N],sy[N];
int match[N];
int dfs(int u)
{
sx[u] = true;
for(int v = 1;v <= m;v ++)
{
if(!sy[v])
{
int t = lx[u] + ly[v] - w[u][v];
if(t == 0)
{
sy[v] = true;
if(match[v] == -1 || dfs(match[v]))
{
match[v] = u;
return 1;
}
}
else
if(lack > t)
lack = t;
}
}
return 0;
}
void KM()
{
int i;
memset(match,-1,sizeof(match));
for(i = 1;i <= n;i ++)
{
lx[i] = -INF;
for(int j = 1;j <= m;j ++)
if(lx[i] < w[i][j])
lx[i] = w[i][j];
}
for(i = 1;i <= m;i ++)
ly[i] = 0;
for(int u = 1;u <= n;u ++)
{
while(1)
{
memset(sx,0,sizeof(sx));
memset(sy,0,sizeof(sy));
lack = INF;
if(dfs(u))
break;
for(i = 1;i <= n;i ++)
if(sx[i])
lx[i] -= lack;
for(i = 1;i <= m;i ++)
if(sy[i])
ly[i] += lack;
}
}
int sum = 0;
for(i = 1;i <= m;i ++)
if(match[i] > -1)
sum += w[match[i]][i];
printf("%d\n",-sum);
}
int main()
{
string s1,s2;
int pl,pc;
int i,j,injury;
while(scanf("%d%d%d",&n,&m,&k) != EOF)
{
pc = pl = 1;
map<string,int> lvbu,caocao;
map<string,int>::iterator it;
for(i = 1;i <= n;i ++)
for(j = 1;j <= m;j ++)
w[i][j] = -INF;
while(k --)
{
cin>>s1>>s2;
scanf("%d",&injury);
it = lvbu.find(s1);
if(it == lvbu.end())
{
lvbu[s1] = pl;
i = pl ++;
}
else
i = it->second;
it = caocao.find(s2);
if(it == caocao.end())
{
caocao[s2] = pc;
j = pc ++;
}
else
j = it->second;
w[i][j] = -injury;
}
KM();
}
return 0;
}