hdu 2813(KM+map)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2813

思路:用STL的map把字符串映射为序号。。。差点就超时了。。。orz。。。弱渣不敢写字典树啊!!!

View Code
 1 #include<iostream>
 2 #include<map>
 3 #include<string>
 4 const int MAXN=222;
 5 const int inf=1<<30;
 6 using namespace std;
 7 int n,m,k;
 8 int match[MAXN];
 9 int lx[MAXN],ly[MAXN];
10 int Map[MAXN][MAXN];
11 bool visitx[MAXN],visity[MAXN];
12 
13 int Hungary(int u){
14     visitx[u]=true;
15     for(int i=1;i<=m;i++){
16         if(!visity[i]&&lx[u]+ly[i]==Map[u][i]){
17             visity[i]=true;
18             if(match[i]==-1||Hungary(match[i])){
19                 match[i]=u;
20                 return true;
21             }
22         }
23     }
24     return false;
25 }
26 
27 
28 void KM_prefect_match(){
29     int tmp;
30     for(int i=1;i<=n;i++){
31         lx[i]=-inf;
32     }
33     memset(ly,0,sizeof(ly));
34     for(int i=1;i<=n;i++){
35         for(int j=1;j<=m;j++){
36             lx[i]=max(lx[i],Map[i][j]);
37         }
38     }
39     for(int i=1;i<=n;i++)
40     {
41         while(1){
42             memset(visitx,false,sizeof(visitx));
43             memset(visity,false,sizeof(visity));
44             if(Hungary(i))
45                 break;
46             else {
47                 tmp=inf;
48                 for(int j=1;j<=n;j++)if(visitx[j]){
49                     for(int k=1;k<=m;k++){
50                         if(!visity[k]&&tmp>lx[j]+ly[k]-Map[j][k]){
51                             tmp=lx[j]+ly[k]-Map[j][k];
52                         }
53                     }
54                 }
55                 for(int j=1;j<=n;j++){
56                     if(visitx[j])
57                         lx[j]-=tmp;
58                 }
59                 for(int j=1;j<=m;j++){
60                     if(visity[j])
61                         ly[j]+=tmp;
62                 }
63             }
64         }
65     }
66 }
67 
68 int main(){
69     while(~scanf("%d%d%d",&n,&m,&k)){
70         for(int i=1;i<=n;i++){
71             for(int j=1;j<=m;j++){
72                 Map[i][j]=-inf;
73             }
74         }
75         memset(match,-1,sizeof(match));
76         map<string,int>mp1,mp2;
77         char s1[22],s2[22];
78         int w,p1=1,p2=1;
79         for(int i=1;i<=k;i++){
80             scanf("%s%s%d",s1,s2,&w);
81             string str1(s1),str2(s2);
82             if(mp1[str1]==0){
83                 mp1[str1]=p1++;
84             }
85             if(mp2[str2]==0){
86                 mp2[str2]=p2++;
87             }
88             Map[mp1[str1]][mp2[str2]]=-w;
89         }
90         KM_prefect_match();
91         int ans=0;
92         for(int i=1;i<=m;i++){
93             if(match[i]!=-1&&Map[match[i]][i]!=-inf)///必不可少的
94                 ans+=Map[match[i]][i];
95         }
96         printf("%d\n",-ans);
97     }
98     return 0;
99 }

 

posted @ 2013-04-03 21:17  ihge2k  阅读(269)  评论(0编辑  收藏  举报