Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 22648 | Accepted: 8781 |
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
1/Σ(to,td)d(to,td)
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. 题意:每输入一个字符串代表一个节点,而节点之间的距离就是不同字符串字对应位置不同的字符个数,然后求最小生成树
不同题意的时候完全不知道怎么做,当知道是距离是什么和是求最小生成树的时候就成了水题
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm> using namespace std;
const int INF = ;
int n;
char str[ + ][];
int edge[ + ][ + ],dist[ + ],vis[ + ];
int weight(char a[],char b[])
{
int ans = ;
for(int i = ; i < ; i++)
if(a[i] != b[i])
ans ++;
return ans;
}
void prime()
{
memset(vis,,sizeof(vis));
for(int i = ; i <= n; i++)
{
dist[i] = edge[][i];
}
vis[] = ;
dist[] = ;
int sum = ;
for(int i = ; i < n; i++)
{
int minn = INF,pos;
for(int j = ; j <= n; j++)
{
if(vis[j] == && dist[j] < minn)
{
minn = dist[j];
pos = j;
}
}
sum += minn;
vis[pos] = ;
for(int j = ; j <= n; j++)
{
if(dist[j] > edge[pos][j])
dist[j] = edge[pos][j];
}
}
printf("The highest possible quality is 1/%d.\n",sum);
}
int main()
{
while(scanf("%d", &n) != EOF)
{
if(n == )
break;
for(int i = ; i <= n; i++)
{
scanf("%s", str[i]);
}
for(int i = ; i < n; i++)
{
for(int j = i + ; j <= n; j++)
{
edge[i][j] = edge[j][i] = weight(str[i],str[j]);
}
}
prime();
}
return ;
}