poj 1789 Truck History(java + prim)

来源:互联网 发布:广州seo顾问 编辑:程序博客网 时间:2024/06/14 22:35
其中的prim()算法完成没有修改的用1258中的prim算法

package prim;

import java.util.Scanner;

/**问题请参考http://poj.org/problem?id=1789
* @author rayli

* @date:2014-7-30 上午8:43:30
* @题意:研究卡车的不同,它会给出各个卡车的一个7位的编号,然后看他们其中有几位是不同的,
* 那么他们的差距就是几,然后求使他们联通的最小的距离和。
*
*/
public class TruckHistory
{

static int map[][];
int ans;

void prim()
{
ans = 0;
int cost[] = new int[map.length];//cost[j]为temp没加入到生成树集合U前节点j到生成树的最小花费

for(int i=0; i<map.length; i++)
{
cost[i] = map[0][i];
}

for(int i=0; i<map.length-1; i++)
{
int minum = Integer.MAX_VALUE;
int tmp = 0;

for(int j=1; j<map.length; j++)
{
if(cost[j] > 0 && minum > cost[j])
{
minum = cost[j];
tmp = j;
}
}

if(ans != Integer.MAX_VALUE)
ans += minum;

cost[tmp] = 0;

for(int j=1; j<map.length; j++)
{
if(map[tmp][j] < cost[j])
{
cost[j] = map[tmp][j];
}
}

}
}

void output()
{
System.out.println("The highest possible quality is 1/" + ans + ".");
}

public static void main(String args[])
{
Scanner cin = new Scanner(System.in);
int n = cin.nextInt();

while(n!=0)
{
char str[][] = new char[n][8];
map = new int[n][n];

//输入字符串
for(int i=0; i<n; i++)
str[i] = cin.next().toCharArray();

//将字符串转化为结点数组
for(int i=0; i<n; i++)
for(int j=i+1; j<n; j++)
{
for(int k=0; k<7; k++)

{
if(str[i][k] != str[j][k])
{
map[i][j]++;
}
}
map[j][i] = map[i][j];
}

TruckHistory th = new TruckHistory();
th.prim();
th.output();

n = cin.nextInt();
}

cin.close();
}
}

原创粉丝点击