最小生成树

二. 最小生成树

Prim 普里姆算法

思路: 该算法采用贪心思想,在图中任意选择一结点构建一颗生成树然后从所有与该生成树相邻的结点中取出最近的结点和边加入到生成树中.直到所有的结点都加入到该生成树中.

算法复杂度 ElogV
一般采用最小优先队列存放剩余的结点,每次从该最小队列中选出与生成树之间最小的结点加入生成树中,同时更新最小队列.

给道题目,原地址戳这

Description

Farmer John has been elected mayor of his town! One of his campaign promises was to bring internet connectivity to all farms in the area. He needs your help, of course.
Farmer John ordered a high speed connection for his farm and is going to share his connectivity with the other farmers. To minimize cost, he wants to lay the minimum amount of optical fiber to connect his farm to all the other farms.
Given a list of how much fiber it takes to connect each pair of farms, you must find the minimum amount of fiber needed to connect them all together. Each farm must connect to some other farm such that a packet can flow from any one farm to any other farm.
The distance between any two farms will not exceed 100,000.

Input

The input includes several cases. For each case, the first line contains the number of farms, N (3 <= N <= 100). The following lines contain the N x N conectivity matrix, where each element shows the distance from on farm to another. Logically, they are N lines of N space-separated integers. Physically, they are limited in length to 80 characters, so some lines continue onto others. Of course, the diagonal will be 0, since the distance from farm i to itself is not interesting for this problem.

Output

For each case, output a single integer length that is the sum of the minimum length of fiber required to connect the entire set of farms.

Sample Input

4
0 4 9 21
4 0 8 17
9 8 0 16
21 17 16 0

Sample Output

28

大概意思就是给你一个n*n二维数组,行列代表点到点的值,求所产生的最小生成树

题解,典型的最小生成树模板,这里采用prim算法实现,下面是已经ac代码

#include <cstdio>  
#include <cstring>  
#include <algorithm>  
#include<iostream>
#include<cmath>
#define LL long long  
using namespace std;
#define xi
#define xx 0x3f3f3f3f//定义一个很大的值,拿已经的最小生成树到其他的点的时候需要用到


int map[106][106];//存图
int vis[10086];//标记当前的节点是否已入最小生成树
int low[10086];//存已知最小生成树带其他节点的最小值
int t;//输入二维数组大小
int prim(){
    int ans=0;//最小生成树的值
    int x=0;//从0节点开始
     memset(vis,0,sizeof(vis));
     for(int a=0;a<t;a++)
         low[a]=map[x][a];//从0到其他节点的最小值
     vis[x]=1;//标记已经使用
     for(int a=0;a<t-1;a++){
      int min=xx;
      for(int a=0;a<t;a++)
      if(vis[a]==0&&min>low[a])
          min=low[a],x=a;//查找最小值,并记录节点
      ans+=min;//加入最小值
      vis[x]=1;
      for(int a=0;a<t;a++)
          if(vis[a]==0&&low[a]>map[x][a])//更新从当前的新节点到其他节点的值,判断是否比已知的最小生成树小,如果小 就更新
             low[a]=map[x][a];
     }
     return ans;
}
int main()
{
#ifdef xin
    freopen("1.txt", "r", stdin);
#endif 

    while(cin>>t&&t){
        for(int a=0;a<t;a++){
            for(int b=0;b<t;b++)
                cin>>map[a][b];
        }
        int sum=prim();
        printf("%d\n",sum);
    }
    return 0;
}

克鲁斯卡尔

克鲁斯卡尔算法每次从剩余的边中选择一个最小的边,如果当前边和已选取的边构成回路,则放弃该并选择下一个最小边。如果不构成回路则将该边以及连接的两个结点加入的生成树中.直到完成整棵生成树的构建.

时间复杂度, ElogE

Description

You are assigned to design network connections between certain points in a wide area. You are given a set of points in the area, and a set of possible routes for the cables that may connect pairs of points. For each possible route between two points, you are given the length of the cable that is needed to connect the points over that route. Note that there may exist many possible routes between two given points. It is assumed that the given possible routes connect (directly or indirectly) each two points in the area.
Your task is to design the network for the area, so that there is a connection (direct or indirect) between every two points (i.e., all the points are interconnected, but not necessarily by a direct cable), and that the total length of the used cable is minimal.

Input

The input file consists of a number of data sets. Each data set defines one required network. The first line of the set contains two integers: the first defines the number P of the given points, and the second the number R of given routes between the points. The following R lines define the given routes between the points, each giving three integer numbers: the first two numbers identify the points, and the third gives the length of the route. The numbers are separated with white spaces. A data set giving only one number P=0 denotes the end of the input. The data sets are separated with an empty line.
The maximal number of points is 50. The maximal length of a given route is 100. The number of possible routes is unlimited. The nodes are identified with integers between 1 and P (inclusive). The routes between two points i and j may be given as i j or as j i.

Output

For each data set, print one number on a separate line that gives the total length of the cable used for the entire designed network.

Sample Input

1 0

2 3
1 2 37
2 1 17
1 2 68

3 7
1 2 19
2 3 11
3 1 7
1 3 5
2 3 89
3 1 91
1 2 32

5 7
1 2 5
2 3 7
2 4 8
4 5 11
3 5 10
1 5 6
4 2 12

0

Sample Output

0
17
16
26

题目大意是给你一个P个节点的图,然后R行的信息,每行表示从开始节点,结束节点,2个节点之间的值

题解,典型的最小生成树模板,这里采用克鲁斯卡尔算法解决,这个算法就是贪心最小的边,然后维护一个并查集。已经ac代码

#include <cstdio>  
#include <cstring>  
#include <algorithm>  
#include<iostream>
#define LL long long  
using namespace std;
#define xi
struct xs
{
    int x,y,v;//开始节点,结束节点,值
    bool operator <(const xs &A)const 
    {
        return v<A.v;//按值得大小进行排序
    }
}s[10086];
int ans=0;
int F[10086];//维护并查集需要
int F1(int x)
{
    return F[x]==x?x:F[x]=F1(F[x]);
}
int main()
{
#ifdef xin
    freopen("1.txt", "r", stdin);
#endif 
    int T;int N;
    while(cin>>T>>N&&T){

    for(int a=0;a<N;a++)
        cin>>s[a].x>>s[a].y>>s[a].v;
    sort(s,s+N);//对值进行排序
    for(int a=0;a<=N;a++)
        F[a]=a;//表示所有的节点都未使用
    int sum=0;
    for(int a=0;a<N;a++)//对已经排序的节点进行遍历,从最小的开始
    {
    int _u=F1(s[a].x);int _v=F1(s[a].y);//判断是否在并查集里面
        if(_v!=_u)
        {
            F[_v]=F[_u];
            sum+=s[a].v;
        }
    }
    cout<<sum<<endl;
    }
    return 0;
}

对于并查集不是很清楚的同学可以瞅这,不难理解,就不赘述了

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,530评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 86,403评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,120评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,770评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,758评论 5 367
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,649评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,021评论 3 398
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,675评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,931评论 1 299
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,659评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,751评论 1 330
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,410评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,004评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,969评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,203评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,042评论 2 350
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,493评论 2 343

推荐阅读更多精彩内容