Today, ACM is rich enough to pay historians to study its history. One thing historians tried to find out is so called derivation plan -- i.e. how the truck types were derived. They defined the distance of truck types as the number of positions with different letters in truck type codes. They also assumed that each truck type was derived from exactly one other truck type (except for the first truck type which was not derived from any other type). The quality of a derivation plan was then defined as
where the sum goes over all pairs of types in the derivation plan such that to is the original type and td the type derived from it and d(to,td) is the distance of the types.
Since historians failed, you are to write a program to help them. Given the codes of truck types, your program should find the highest possible quality of a derivation plan.
1.将第一个点放入最小生成树的集合中(标记visit[i]=1意思就是最小生成树集合)。
2.从第二个点开始,初始化lowcost[i]为跟1点相连(仅仅相连)的边的权值(lowcost[i]不是这个点的最小权值!在以后会逐步更新)。
3.找最小权值的边。
从第二点开始遍历,如果不是最小生成树的集合的点,则找出从2到n的最小权值(lowcost[j])。
4.将找出来的最小权值的边的顶点加入最小生成树的集合中(标记visit[i] = 1),权值想加。
5.更新lowcost[j]集合。
假设第一次:lowcost[2]代表与1相连的点的权值,现在加入了k点。则比较k点与2点的边map[k][2]和lowcost[2]的大小,若lowcost[2]大,则lowcost[2] = map[k][2]。(关键步骤:实质就是每在最小生成树集合中加入一个点就需要把这个点与集合外的点比较,不断的寻找两个集合之间最小的边)
6.循环上述步骤,指导将全部顶点加入到最小生成树集合为止。
***************************************************************************************************************************


1 #include<iostream> 2 #include<string> 3 #include<cmath> 4 #include<cstring> 5 #include<cstdio> 6 #include<queue> 7 using namespace std; 8 int map[2010][2010]; 9 char str[2010][10]; 10 int vis[2010],n; 11 void init() 12 { 13 memset(map,0,sizeof(map)); 14 for(int it=0;it<n;it++) 15 for(int jt=it+1;jt<n;jt++) 16 for(int kt=0;kt<7;kt++) 17 if(str[it][kt]!=str[jt][kt]) 18 { 19 map[it][jt]++; 20 map[jt][it]++; 21 } 22 } 23 int prime() 24 { 25 int lowcost[2010],lowset[2010]; 26 int i,j,k,sum=0; 27 memset(vis,0,sizeof(vis)); 28 for(i=0;i<n;i++)//初始化 29 { 30 lowcost[i]=map[0][i]; 31 lowset[i]=0; 32 } 33 vis[0]=1; 34 for(i=1;i<n;i++) 35 { 36 j=0; 37 while(vis[j])j++; 38 for(k=0;k<n;k++)//找到最短边 39 { 40 if(!vis[k]&&lowcost[k]<lowcost[j])j=k; 41 } 42 sum+=map[j][lowset[j]]; 43 vis[j]=1; 44 for(k=0;k<n;k++)//更新最短边 45 { 46 if(!vis[k]&&lowcost[k]>map[j][k]) 47 { 48 lowcost[k]=map[j][k]; 49 lowset[k]=j; 50 } 51 } 52 53 } 54 return sum; 55 } 56 int main() 57 { 58 int i,j,k; 59 while(scanf("%d",&n)&&n) 60 { 61 getchar(); 62 for(i=0;i<n;i++) 63 { 64 scanf("%s",str[i]); 65 } 66 init(); 67 printf("The highest possible quality is 1/%d.\n",prime()); 68 } 69 return 0; 70 }