POJ1258-Agri-Net

转载请注明出处:優YoU http://user.qzone.qq.com/289065406/blog/1299324000

提示:又是一题求最小生成树的总权值,继续Prim....

 

 1 //Memory Time 
2 //300K 32MS
3
4 #include<iostream>
5 using namespace std;
6
7 const int inf=100001; //无限大
8
9 int n; //农场数量
10 int dist[101][101];
11
12 int prim(void)
13 {
14 int s=1;
15 int m=1;
16 bool u[101]={false};
17 u[s]=true;
18
19 int min_w;
20 int prim_w=0;
21 int point;
22 int low_dis[101];
23
24 /*Initial*/
25
26 for(int i=1;i<=n;i++)
27 low_dis[i]=inf;
28
29 /*Prim Algorithm*/
30
31 while(true)
32 {
33 if(m==n)
34 break;
35
36 min_w=inf;
37 for(int i=2;i<=n;i++)
38 {
39 if(!u[i] && low_dis[i]>dist[s][i])
40 low_dis[i] = dist[s][i];
41 if(!u[i] && min_w>low_dis[i])
42 {
43 min_w = low_dis[i];
44 point=i;
45 }
46 }
47 s=point;
48 u[s]=true;
49 prim_w+=min_w;
50 m++;
51 }
52 return prim_w;
53 }
54
55 int main(void)
56 {
57 while(cin>>n)
58 {
59 /*Input*/
60
61 for(int i=1;i<=n;i++)
62 for(int j=1;j<=n;j++)
63 cin>>dist[i][j];
64
65 /*Prim Algorithm & Output*/
66
67 cout<<prim()<<endl;
68 }
69 return 0;
70 }

你可能感兴趣的:(poj)