One fight one
Problem Description
Lv Bu and his soldiers are facing a cruel war——Cao Cao had his best generals just miles away.
There’s little time , but Lv Bu is unaware of how to arrange his warriors , what he know is that he have n brave generals while Cao Cao has m , and he has k fights to choose from , he’d like to make all his n warriors participate in the battle but get the least injuries . Lv Bu is happy because there is always a good solution . So , now is your task to tell Lv Bu the least injuries his troop would get.
No one could take part in two fights.
Input
Multiple cases. For each case ,there are three integers in the first line , namely n,m (1<=n<=m<=200)and k (n<=k<=m*n).
The next k lines are the information about k possible fights , for each line are two strings (no more than 20 characters ) and an integer. The first string indicates Lv Bu’s general and the second , of course , Cao Cao’s , and the integer is the injury Lv Bu’s general would get if this fight were chosen.
Output
One integer , the least injuries Lv Bu’s generals would get.
Sample Input
2 3 5 LvBu ZhangFei 6 LvBu GuanYu 5 LvBu XuChu 4 ZhangLiao ZhangFei 8 ZhangLiao XuChu 3
Sample Output
Author
shǎ崽
Source
One Fight One KM算法
#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;
const int MAXN = 202;
const int inf = 999999999;
int lx[MAXN],ly[MAXN],linky[MAXN],w[MAXN][MAXN];
bool visx[MAXN],visy[MAXN];
int N,M,slack;
// The period of Hungary
bool find(int x){
visx[x]=true;
int y;
for(y=0;y<M;y++){
if(visy[y] || w[x][y]==inf) continue;
int t=w[x][y]-lx[x]-ly[y];
if(t==0){
visy[y]=true;
if(linky[y]==-1 || find(linky[y])){
linky[y]=x;
return true;
}
}
else if(slack>t) slack=t;
}
return false;
}
// KM algorithm to solve the perfect match
int KM(){
memset(linky,-1,sizeof(linky));
memset(ly,0,sizeof(ly));
for(int i=0;i<N;i++){
lx[i]=w[i][0];
for(int j=1;j<M;j++)
if(lx[i]>w[i][j]) lx[i]=w[i][j];
}
for(int x=0;x<N;x++){
while(1){
memset(visx,0,sizeof(visx));
memset(visy,0,sizeof(visy));
slack=inf;
if(find(x)) break;
for(int i=0;i<N;i++)
if(visx[i]) lx[i]+=slack;
for(int i=0;i<M;i++)
if(visy[i]) ly[i]-=slack;
}
}
int ans=0;
for(int i=0;i<M;i++)
if(linky[i]!=-1)
ans+=w[linky[i]][i];
return ans;
}
//using Trie Tree to build the graph
int nodecnt;
int root;
struct trie{
int next[256];
int k;
}node[10000];
int NewNode(){
memset(node[nodecnt].next,-1,sizeof(int)*256);
node[nodecnt].k=-1;
return nodecnt++;
}
int trie_insert(char *s,int &cnt){
int x=root;
for(int i=0;s[i];i++){
if(node[x].next[s[i]]==-1)
node[x].next[s[i]]=NewNode();
x=node[x].next[s[i]];
}
if(node[x].k==-1) node[x].k=cnt++;
return node[x].k;
}
int main(){
int K;
while(~scanf("%d%d%d",&N,&M,&K)){
for(int i=0;i<N;i++)
for(int j=0;j<M;j++)
w[i][j]=inf;
int ww;
char s1[50],s2[50];
int acnt=0,bcnt=0;
int a,b;
nodecnt=0;
root=NewNode();
while(K--){
scanf("%s%s%d",s1,s2,&ww);
a=trie_insert(s1,acnt);
b=trie_insert(s2,bcnt);
w[a][b]=ww;
}
printf("%d\n",KM());
}
return 0;
}