ZOJ 1406 解题报告

ZOJ 1406 解题报告
Prim算法.
Code
 1#include <iostream>
 2using namespace std;
 3
 4const int N = 28;
 5const int UNLINK = 0x7fffffff;
 6int g[N][N];
 7int weight[N];
 8bool visited[N];
 9
10int _tmain(int argc, _TCHAR* argv[])
11{
12    int vertex, t_vertex;
13    while(cin >> t_vertex && t_vertex != 0)
14    {
15        vertex = t_vertex;
16        memset(visited, falsesizeof(visited));
17
18        for(int i = 0; i < vertex; ++i)
19        {
20            weight[i] = UNLINK;
21            for(int j = 0; j < vertex; ++j)
22            {
23                g[i][j] = UNLINK;
24            }

25        }

26
27        char v;
28        int num, t_num;
29        while(--t_vertex)
30        {
31            cin >> v >> t_num;
32            num = t_num;
33
34            char vl;
35            int edge;
36            while(t_num--)
37            {
38                cin >> vl >> edge;
39                g[(int)(v - 'A')][(int)(vl - 'A')] = edge;
40                g[(int)(vl - 'A')][(int)(v - 'A')] = edge;
41            }

42        }

43
44        for(int i = 0; i < vertex; ++i)
45        {
46            weight[i] = g[0][i];
47        }

48        visited[0= true;
49        int min(UNLINK), nearest(-1), total_weight(0);
50
51        for(int i = 0; i < vertex; ++i)
52        {
53            min = UNLINK;
54            nearest = -1;
55            for(int j = 0; j < vertex; ++j)
56            {
57                if(min > weight[j] && !visited[j])
58                {
59                    min = weight[j];
60                    nearest = j;
61                }

62            }

63            visited[nearest] = true;
64            total_weight += weight[nearest];
65
66            for(int j = 0; j < vertex; ++j)
67            {
68                if(g[nearest][j] < weight[j])
69                {
70                    weight[j] = g[nearest][j];
71                }

72            }

73        }

74
75        cout << total_weight << endl;
76    }

77    return 0;
78}

79
80

你可能感兴趣的:(ZOJ 1406 解题报告)