題目鏈接:http://poj.org/problem?id=1789
Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 16492 | Accepted: 6344 |
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 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.
Input
Output
Sample Input
4 aaaaaaa baaaaaa abaaaaa aabaaaa 0
Sample Output
The highest possible quality is 1/3.
題意:有n個長度爲7的字符串,定義它們之間的距離爲不同字符的個數(字符串同一位置進行比較,有不同則距離加1)。除了第一個以外,每一個字符串都繼承自另一個,
求一種繼承方案使得總距離最小。
將每個字符串視作一個點,問題就轉化成了求圖的最小生成樹。
由於每兩個點之間都有距離,所以用Prim算法較爲合適。(複雜度O(n*n))
注意格式以及最後的“.”
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
using namespace std;
const int inf=0x3f3f3f3f;
int g[2005][2005],dis[2005];
char s[2005][10];
int n;
int prim(int n,int m)//Prim求最小生成樹
{
memset(dis,0x3f,sizeof(dis));
int now,min_code,min_edge,ans;
now=0;ans=0;
for (int i=0;i<n-1;i++)
{
dis[now]=-1;
min_edge=inf;
for (int j=0;j<n;j++)
{
if (j!=now&&dis[j]>=0)
{
dis[j]=min(dis[j],g[now][j]);
if (dis[j]<min_edge)
{
min_edge=dis[j];
min_code=j;
}
}
}
ans+=min_edge;
now=min_code;
}
return ans;
}
int main()
{
while (scanf("%d",&n)!=EOF&&n!=0)
{
memset(g,0,sizeof(g));
for (int i=0;i<n;i++)
{
scanf("%s",s[i]);
}
for (int i=0;i<n-1;i++)//窮舉求出兩兩之間距離
{
for (int j=i+1;j<n;j++)
{
for (int k=0;k<7;k++)
{
if (s[i][k]!=s[j][k]) ++g[i][j];
}
g[j][i]=g[i][j];
}
}
printf("The highest possible quality is 1/%d.\n",prim(n,n));
}
return 0;
}