就是简单的最小生成树,本来用卡尔(Kruskal)算法写也没什么难的,可是偏偏要求用Prim写,搞得我很纠结,总算明白为什么白书里不说它了,因为写起来真的很麻烦,效率也不见得高多少。

 1 #include <stdio.h>
 2 #include <string.h>
 3 #include <queue>
 4 using namespace std;
 5 int a[105][105];
 6 bool vis[105];
 7 typedef struct
 8 {
 9     int a,b,w;
10     void init(int x,int y,int z)
11     {a = x;b= y; w = z;}
12 }Edge;
13 bool operator<(Edge m,Edge n)
14 {
15     return m.w > n.w;
16 }
17 int main()
18 {
19     int n,i,j,f,cnt,ans;
20     Edge t;
21     while(~scanf("%d",&n))
22     {
23         priority_queue <Edge> q;
24         memset(vis,0,sizeof(vis));
25         for(i = 1; i <= n; i++)
26             for(j = 1; j <= n; j++)
27                 scanf("%d",&a[i][j]);
28         cnt = 1;
29         ans = 0;
30         vis[1] = 1;
31         for(j = 1; j <= n; j++)
32             if(!vis[j])
33             {
34                 t.init(1,j,a[1][j]);
35                 q.push(t);
36             }
37         while(cnt < n)
38         {
39             t = q.top();
40             q.pop();
41             if(!(vis[t.a] && vis[t.b]))
42             {
43                 ans += t.w;
44                 cnt++;
45             //    printf("%d\n",t.w);
46                 f = vis[t.a] ?t.b :t.a ;
47                 vis[f] = 1;
48             for(j = 1; j <= n; j++)
49                 if(!vis[j])
50                 {
51                     t.init(f,j,a[f][j]);
52                     q.push(t);
53                 }
54             }
55         }
56         printf("%d\n",ans);
57     }
58     return 0;
59 }