POJ 1789 Truck History

Prim 最小生成树模板,直接上代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/*
poj 1789
16004K 344MS
*/
#include<cstdio>
#include<iostream>
#include<cstring>

#define MAXN 2005

using namespace std;

int n,gra[MAXN][MAXN],low_cost[MAXN];
char str[MAXN][8];

void init()
{
for(int i = 1;i <= n;i ++)
{
for(int j = i + 1;j <= n;j ++)
{
int cnt = 0;
for(int k = 0;k < 7;k ++)
cnt += (str[i][k] != str[j][k]);
gra[i][j] = gra[j][i] = cnt;
}
}
for(int i = 1;i <= n;i ++)
low_cost[i] = 0xfffffff;
}

int calc()
{
bool mark[MAXN] = {false};
int sum = 0,s = 1,m = 1,tmin = 0xfffffff,ti = 0;
mark[s] = true;
while(m < n)
{
tmin = 0xfffffff; ti = 0;
for(int i = 2;i <= n;i ++)
{
if(!mark[i] && low_cost[i] > gra[s][i])
low_cost[i] = gra[s][i];
if(!mark[i] && tmin > low_cost[i])
{
tmin = low_cost[i];
ti = i;
}
}
s = ti;
mark[s] = true;
sum += tmin;
m ++;
}
return sum;
}

int main()
{
while(cin>>n && n)
{
memset(gra , 0 , sizeof(gra));
memset(low_cost , 0 , sizeof(low_cost));
for(int i = 1;i <= n;i ++)
scanf("%s",str[i]);
init();
printf("The highest possible quality is 1/%d.\n",calc());
}
return 0;
}
作者

Ferris Tien

发布于

2014-05-15

更新于

2024-10-19

许可协议