码迷,mamicode.com
首页 > 其他好文 > 详细

1212 无向图最小生成树

时间:2017-09-11 23:01:55      阅读:199      评论:0      收藏:0      [点我收藏+]

标签:size   ble   bre   htm   clu   style   cos   enter   基础   

1212 无向图最小生成树技术分享

基准时间限制:1 秒 空间限制:131072 KB 分值: 0 难度:基础题
技术分享 收藏
技术分享 关注
N个点M条边的无向连通图,每条边有一个权值,求该图的最小生成树。
 
Input
第1行:2个数N,M中间用空格分隔,N为点的数量,M为边的数量。(2 <= N <= 1000, 1 <= M <= 50000)
第2 - M + 1行:每行3个数S E W,分别表示M条边的2个顶点及权值。(1 <= S, E <= N,1 <= W <= 10000)
Output
输出最小生成树的所有边的权值之和。
Input示例
9 14
1 2 4
2 3 8
3 4 7
4 5 9
5 6 10
6 7 2
7 8 1
8 9 7
2 8 11
3 9 2
7 9 6
3 6 4
4 6 14
1 8 8
Output示例
37

用prim算法可以完成.
 1 #include <iostream>
 2 #include <cstring>
 3 #include <cstdio>
 4 #include <algorithm>
 5 #define N 1005
 6 #define inf 0x3f3f3f3f
 7 #define mem(a) memset(a,0,sizeof(a))
 8 using namespace std;
 9 int cost[N][N];//表示两点之间的距离,不存在则设为inf
10 int mincost[N];//从x集合出发到每个顶点的最小值
11 bool used[N];//判断是否在集合中的布尔数组
12 int n,m;
13 
14 int prim(){
15   for(int i=0;i<n;i++){//初始化mincost数组和used布尔数组
16     mincost[i]=inf;
17     used[i]=false;
18   }
19   mincost[0]=0;//赋给其初值
20   long long int ans=0;
21 
22   while(true){
23     int v=-1;
24     //从不属于x的顶点中选取从x到其权值最小的顶点
25     for(int u=0;u<n;u++)
26       if(!used[u]&&(v==-1||mincost[u]<mincost[v]))
27         v=u;
28 
29     if(v==-1)
30       break;//条件成立则说明所有的点都已经加入
31     used[v]=true;//把顶点加入
32     ans+=mincost[v];//把边的长度加到结果里
33 
34     for(int u=0;u<n;u++){
35       if(!used[u])
36         mincost[u]=min(mincost[u],cost[v][u]);
37     }
38   }
39   return ans;
40 }
41 int main(){
42   cin>>n>>m;
43   int x,y,z;
44   memset(cost,inf,sizeof(cost));
45   while(m--){
46     scanf("%d%d%d",&x,&y,&z);
47     cost[--x][--y]=z;
48     cost[y][x]=z;
49   }
50   long long int k=prim();
51   cout<<k<<endl;
52   return 0;
53 }

 

 

1212 无向图最小生成树

标签:size   ble   bre   htm   clu   style   cos   enter   基础   

原文地址:http://www.cnblogs.com/zllwxm123/p/7506947.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!