poj 1789 Truck History

prim求最小生成树。

 1 #include<stdio.h>

 2 #include<string.h>

 3 #define INF 100000000

 4 #define MAXN 2100

 5 

 6 int n, v[MAXN], low[MAXN], d[MAXN][MAXN];

 7 char s[MAXN][10];

 8 

 9 void prim()

10 {

11     int ans = 0;

12     memset(v, 0, sizeof(v));

13     v[0] = 1;

14     for(int i = 1; i < n; i ++) low[i] = d[0][i];

15     for(int i = 1; i < n; i ++)

16     {

17         int min = INF, p;

18         for(int j = 0; j < n; j ++)

19         if(!v[j] && min > low[j]) min = low[p=j];

20         ans += min;

21         v[p] = 1;

22         for(int j = 0; j < n; j ++)

23         if(!v[j] && low[j] > d[p][j]) low[j] = d[p][j];

24     }

25     printf("The highest possible quality is 1/%d.\n",ans);

26 }

27 void init()

28 {

29     while(scanf("%d",&n))

30     {

31         if(n == 0) break;

32         for(int i = 0; i < n; i ++)

33             scanf("%s",s[i]);

34         for(int i = 0; i < n; i ++)

35         {

36             for(int j = i+1; j < n; j ++)

37             {

38                 int t = 0;

39                 for(int k = 0; k < 7; k ++)

40                     if(s[i][k] != s[j][k]) t ++;

41                 d[i][j] = t;

42                 d[j][i] = t;

43             }

44         }

45         prim();

46     }

47 }

48 int main()

49 {

50     init();

51     return 0;

52 }

你可能感兴趣的:(history)