One fihgt one
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 998 Accepted Submission(s): 302

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.
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.
2 3 5 LvBu ZhangFei 6 LvBu GuanYu 5 LvBu XuChu 4 ZhangLiao ZhangFei 8 ZhangLiao XuChu 3
8
Statistic | Submit | Discuss | Back
#include<cstdio>
#include<string.h>
#include<iostream>
#include<map>
#include<string>
using namespace std;
const int INF=1<<25-1;
int mat[250][250],lx[250],ly[250];//顶点标号
bool sx[250],sy[250];//是否已经搜索过
int link[250],stack[250],cas1,cas2,n,m;
bool path(int k)//从x[k]寻找增广路
{
sx[k]=true;
for(int i=0; i<m; i++)
{
if(mat[k][i]!=-INF&&!sy[i])
{
int t=ly[i]+lx[k]-mat[k][i];
if(t==0)
{
sy[i]=1;
if(link[i]==-1||path(link[i]))
{
link[i]=k;
return true;
}
}
else if(stack[i]>t) stack[i]=t;
}
}
return false;
}
int BestMatch()//求解最小权匹配
{
int d,sum;
memset(ly,0,sizeof(ly));
memset(link,-1,sizeof(link));
for(int i=0; i<n; i++)
{
lx[i]=-1<<24; //x中顶点i的编号为与i关联的Y中边的最大权重
for(int j=0; j<m; j++) if(lx[i]<mat[i][j]&&mat[i][j]!=-INF) lx[i]=mat[i][j];
}
for(int k=0; k<n; k++)
{
for (int i=0; i<m; i++) stack[i]=10000000;
while(1)
{
memset(sx,0,sizeof(sx));
memset(sy,0,sizeof(sy));
if(path(k)) break;//匹配成功
d=10000000;
for(int i=0; i<m; i++)if (!sy[i]&&stack[i]<d) d=stack[i];
for(int i=0; i<n; i++) if(sx[i]) lx[i]-=d;
for(int i=0; i<m; i++) if(sy[i]) ly[i]+=d;
else stack[i]-=d;
}
}
sum=0;
for(int i=0; i<m; i++)
if(link[i]!=-1)
sum+=mat[link[i]][i];
//注意这里本来是求的最大权匹配,这里取反即为最小权匹配(因为临街矩阵中的边的权值也取反了)
return -sum;
}
int main()
{
int k;
string s1,s2;
int c,j1,j2;
while(scanf("%d%d%d",&n,&m,&k)!=EOF)
{
memset(mat,0,sizeof(mat));
map<string,int>lv,cao;
map<string,int>::iterator it;
cas1=0,cas2=0;
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
mat[i][j]=-INF;
for(int i=0; i<k; i++)
{
cin>>s1>>s2>>c;
it=lv.find(s1);
if(it==lv.end()) lv[s1]=cas1,j1=cas1++;
else j1=it->second;
it=cao.find(s2);
if(it==cao.end()) cao[s2]=cas2,j2=cas2++;
else j2=it->second;
mat[j1][j2]=-c;
}
printf("%d/n",BestMatch());
}
return 0;
}