天天看點

ZOJ 2158 && POJ 1789 Truck History (經典MST)

連結:http://poj.org/problem?id=1789 或  http://acm.zju.edu.cn/onlinejudge/showproblem.do?problemid=1158

description

advanced cargo movement, ltd. uses trucks of different types. some trucks are used for vegetable delivery, other for furniture, or for bricks. the company has its own code describing each type of a truck. the code is simply a string of exactly seven lowercase

letters (each letter on each position has a very special meaning but that is unimportant for this task). at the beginning of company‘s history, just a single truck type was used but later other types were derived from it, then from the new types another types

were derived, and so on. 

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

the input consists of several test cases. each test case begins with a line containing the number of truck types, n, 2 <= n <= 2 000. each of the following n lines of input contains one truck type code (a string of seven lowercase letters). you may assume that

the codes uniquely describe the trucks, i.e., no two of these n lines are the same. the input is terminated with zero at the place of number of truck types.

output

for each test case, your program should output the text "the highest possible quality is 1/q.", where 1/q is the quality of the best derivation plan.

sample input

sample output

分析: 要使派生方案的優劣值最大,那麼分母的值當然是要越小越好,而且要求考慮所有類型對(t0, td)的距離,使得最終派生方案中每種卡車類型都是由其他一種卡車類型派生出來的(除了最初的卡車類型之外)這樣,将每種卡車類型了解成一個無向網中的頂點,所要求的最佳派生方案就是求最小生成樹,而上述表達式中的分母就是最小生成樹的權值;

代碼:

繼續閱讀