Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 21736 | Accepted: 8459 |
Description
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 t o is the original type and t d the type derived from it and d(t o,t d) 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.
Input
Output
Sample Input
4 aaaaaaa baaaaaa abaaaaa aabaaaa 0
Sample Output
The highest possible quality is 1/3.
Source
题目大意:
随着货物流通的发展,我们可以使用不同类型的货车。
每个货车公司都有属于自己的编号去描述不同类型的货车,其中编号由7个小写字母组成(每个字母在自己的位置上都有特殊的意义,但对这个任务不重要)。
公司开始之初,只有一个货车类型编号,之后的货车编号都来源它。
ACM 想要学习这个公司的历史,看看这个货车类型编号是如何发展的。
假设两个不同类型的货车的distance(翻译为距离比较好理解)为:
两个货车编号,对应位置上,不同字母的数量。
例如:
A车编号为:aaaaaaa
B车编号为:baaaaaa
C车编号为:abaaaaa
那么A与B的距离为:dis(A,B)=1,dis(A,C)=1,dis(B,C)=2。
我们可以认为,除了初始编号外,其他的每一个编号都来源于另一个编号。
这个计划的质量定义为:1/Σ(to,td)d(to,td)
也就是距离总和的倒数。
求这个派生计划的最高质量。
分子为1,分母越小,分数越大,反之亦然。
所以我们要求的是最小的距离总和。
也就是求最小生成树。
因为源编号(根节点)可以任意,其他结点只要可达就行。
即除源编号外,其他编号可以由源编号产生,也可以由其他任意编号产生。
直接用Pirm求最小生成树即可。
#include <cstdio>
#include <cstring>
const int INF = 0x3f3f3f3f;
const int maxn = 2010;
char str[maxn][10];
int map[maxn][maxn],dis[maxn];
bool mark[maxn];
int n;
int weight(int ti,int tj)
{
int k,count=0;
for(k=0;k<7;++k)
if(str[ti][k]!=str[tj][k])
count++;
return count;
}
void init()
{
int i,j;
memset(map,INF,sizeof(map)); //因为是完全图,所以可以不初始化(用过的顶点都会被标记)
for(i=1;i<n;++i)
for(j=i+1;j<=n;++j)
map[i][j]=map[j][i]=weight(i,j);
}
void prim()
{
int i,j,minm,id,sum;
memset(mark,0,sizeof(mark));
for(i=1;i<=n;++i)
{
dis[i]=map[1][i];
}
mark[1]=true;
sum=0;
for(i=1;i<n;++i)
{
minm=INF;
for(j=1;j<=n;++j)
{
if(dis[j]<minm&&!mark[j])
{
minm=dis[j];
id=j;
}
}
sum+=minm;
mark[id]=true;
for(j=1;j<=n;++j)
{
if(dis[j]>map[id][j]&&!mark[j])
dis[j]=map[id][j];
}
}
printf("The highest possible quality is 1/%d.\n",sum);
}
int main()
{
int i;
while(scanf("%d",&n),n)
{
for(i=1;i<=n;++i)
scanf("%s",str[i]);
init();
prim();
}
return 0;
}