POJ-1258 Agri-Net---MST裸题Prim

题目链接:

https://vjudge.net/problem/POJ-1258

题目大意:

求MST

思路:

由于给的是邻接矩阵,直接prim算法

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<algorithm>
 5 #include<cmath>
 6 #include<queue>
 7 #include<stack>
 8 #include<map>
 9 #include<sstream>
10 using namespace std;
11 typedef long long ll;
12 const int maxn = 2e3 + 10;
13 const int INF = 1 << 30;
14 int dir[4][2] = {1,0,0,1,-1,0,0,-1};
15 int T, n, m, x;
16 int Map[maxn][maxn];//存图
17 int lowcost[maxn], mst[maxn];
18 void prim(int u)//最小生成树起点
19 {
20     int sum_mst = 0;//最小生成树权值
21     for(int i = 1; i <= n; i++)//初始化两个数组
22     {
23         lowcost[i] = Map[u][i];
24         mst[i] = u;
25     }
26     mst[u] = -1;//设置成-1表示已经加入mst
27     for(int i = 1; i <= n; i++)
28     {
29         int minn = INF;
30         int v = -1;
31         //在lowcost数组中寻找未加入mst的最小值
32         for(int j = 1; j <= n; j++)
33         {
34             if(mst[j] != -1 && lowcost[j] < minn)
35             {
36                 v = j;
37                 minn = lowcost[j];
38             }
39         }
40         if(v != -1)//v=-1表示未找到最小的边,
41         {//v表示当前距离mst最短的点
42             //printf("%d %d %d\n", mst[v], v, lowcost[v]);//输出路径
43             mst[v] = -1;
44             sum_mst += lowcost[v];
45             for(int j = 1; j <= n; j++)//更新最短边
46             {
47                 if(mst[j] != -1 && lowcost[j] > Map[v][j])
48                 {
49                     lowcost[j] = Map[v][j];
50                     mst[j] = v;
51                 }
52             }
53         }
54     }
55     //printf("weight of mst is %d\n", sum_mst);
56     cout<<sum_mst<<endl;
57 }
58 int main()
59 {
60     while(cin >> n && n)
61     {
62         for(int i = 1; i <= n; i++)
63         {
64             for(int j = 1; j <= n; j++)
65                 scanf("%d", &Map[i][j]);
66         }
67         prim(1);
68     }
69 
70     return 0;
71 }

 

posted @ 2018-04-05 17:25  _努力努力再努力x  阅读(149)  评论(0编辑  收藏  举报