Time Limit: 2000MS Memy Limit: 65536K
Description
Today, ACM is rich enough to pay histians to study its histy. One thing histians 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 exactly one other truck type (except f the first truck type which was not derived 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 iginal type td the type derived it d(to,td) is the distance of the types.
Since histians 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.
Input
Output
Sample Input
4
aaaaaaa
baaaaaa
abaaaaa
aabaaaa
0
Sample Output
The highest possible quality is 1/3.
题目大意是就是给出n个长度为7的字符串,每个字符串代表一个车,定义车的距离是两个字符串间不同字母的个数,题目要求的数是不同的车的距离的最小值,即所求的就是最小生成树
关于数据的输入和输出详见样例,要注意输出完数据后还有个""."",这题是一个稠密图,用Prim算法比较好。
转载的~~~:
#include <stdio.h>
#include <memory.h>
#include <algorithm>
#include <iostream>
using namespace std;
// 最大值
#define INF 99999999
// 最多的边数
#define N 2000
// 路径储存
int road[N][N];
char type[N][8];
int main()
{
int n,m,count;
int i,j,k,l;
int mink,min,res;
while(true) {
scanf("%d",&n);
if(!n)
break;
// 以下是将字符串转换为邻接矩阵
getchar();
for(i = 0; i < n; i++)
gets(type[i]);
for(i = 0; i < n; i++) {
road[i][i] = -1;
for(j = i + 1; j < n;j++) {
count = 0;
for(k = 0; k < 7; k++)
if(type[i][k] != type[j][k])
count++;
road[i][j] = road[j][i] = count;
}
}
//Prim最小生成树
res = 0;
int lesscost[N];
for(i = 0; i < n;i++)
lesscost[i] = road[0][i]; //初始化
for( i = 1; i < n ;i++) {
min = INF;
for(j = 0; j < n; j++)
if(lesscost[j] >= 0 && lesscost[j] < min) {
min = lesscost[j];
mink = j;
} //lesscost中最小边位置mink
res += min;
// 将刚加入集合的节点的所有边和现有边做一个比较,保留小的边
for(j = 0; j < n;j++)
if(lesscost[j] > road[mink][j]) //比较lesscost中值与第mink行值,取较小值更新losscost
lesscost[j] = road[mink][j];
}
printf("The highest possible quality is 1/%d.\n",res);
}
}
aaaaaaa -1 1 1 1
baaaaaa 1 -1 2 2
abaaaaa 1 2 -1 2
aabaaaa 1 2 2 -1
lesscost:
-1 1 1 1
1 //①lesscost中最小边位置k=1 (初始为找到到点a距离最小的点k,后为使dlmin的k')
res= 1 //②更新res+=lesscost[k] (加入边长d(a,k))
-1 -1 1 1 //③比较lesscost中值与第k行值,取较小值更新losscost,再做①
(记录剩下各点k'到边d(a,k)两端a,k距的最小距d(l,k')=min{d(a,k'),d(k,k')},存入dl)
2 -1 -1 -1 1
3 -1 -1 -1 -1
res= 1 + 1 + 1
本文探讨了如何使用最小生成树算法解决TruckHistory问题,通过实例解析了算法的应用过程,并给出了详细的数据输入输出规范。该文不仅介绍了最小生成树的基本概念,还提供了算法的具体实现步骤,包括邻接矩阵的构建、Prim算法的运用以及最终结果的输出形式。
955

被折叠的 条评论
为什么被折叠?



