【最小生成树】【Kruskal算法(含并查集的使用)(适用于稀疏图)】【模板】讲解 + 例题1 POJ 2485 Highways + 例题2 POJ - 1287 Networking

Kruskal算法

  • 每次选取权重最小的边,如果这条边是安全的,那么就把它加入到生成树中,直到选取n-1条表示算法结束(若找不到,则说明不存在最小生成树MST)。
  • 所谓安全边,指的是这条边连接的两个结点,原本是处于不同的树上的。(否则就形成了回路)
  • 很显然,Kruscal算法中用到了并查集,判断某一条边是否连接了两棵不同的树。

模板一代码:

(并查集部分省略)
重载符号的使用见博客

struct Edge
{
    int u, v, w;// 注意这里要存完整的两个端点
    friend bool operator < (Edge a, Edge b)//也常用优先队列
    {
        return a.w < b.w;//要注意重载符号的使用!!!
    }
} e[MAXN * MAXN];//注意这里要开MAXN * MAXN,因为每一个节点到其他节点都可能存在边


int edgeCount = 0;//记录边的条数
sort(e, e + edgeCount);
int times = 0;//记录选取边的条数
for(int i = 0; i < edgeCount; i++)
{
    if(merge(e[i].u, e[i].v))
    {
        //按题目要求操作,如求最长的边,或求路的总长
        if(++times == n - 1)//选取n-1条边后终止
            break;
    }
}



例题一: POJ 2485 Highways

The island nation of Flatopia is perfectly flat. Unfortunately, Flatopia has no public highways. So the traffic is difficult in Flatopia. The Flatopian government is aware of this problem. They’re planning to build some highways so that it will be possible to drive between any pair of towns without leaving the highway system.

Flatopian towns are numbered from 1 to N. Each highway connects exactly two towns. All highways follow straight lines. All highways can be used in both directions. Highways can freely cross each other, but a driver can only switch between highways at a town that is located at the end of both highways.

The Flatopian government wants to minimize the length of the longest highway to be built. However, they want to guarantee that every town is highway-reachable from every other town.

Input
The first line of input is an integer T, which tells how many test cases followed.

The first line of each case is an integer N (3 <= N <= 500), which is the number of villages. Then come N lines, the i-th of which contains N integers, and the j-th of these N integers is the distance (the distance should be an integer within [1, 65536]) between village i and village j. There is an empty line after each test case.

Output

For each test case, you should output a line contains an integer, which is the length of the longest road to be built such that all the villages are connected, and this value is minimum.
Sample Input

1

3
0 990 692
990 0 179
692 179 0

Sample Output

692

Hint

Huge input,scanf is recommended.

题意:
有n个城市,每一行给的数据是第i座城市到 1 ~ n座城市的距离,要在城市间建公路,使各个城市相通,求最短路径中 最长的一条边的长度。

思路:
最小生成树模板题

AC代码:

#include <stdio.h>
#include <iostream>
#include <algorithm>
using namespace std;

const int MAXN = 550;
int n, fa[MAXN];
struct Edge
{
    int u, v, w;
    friend bool operator < (Edge a, Edge b)
    {
        return a.w < b.w;
    }
} e[MAXN * MAXN];

void init()
{
    for(int i = 0; i <= n; i++)
    {
        fa[i] = i;
    }
}

int find(int x)
{
    return fa[x] == x ? x : fa[x] = find(fa[x]);
}

bool merge(int x, int y)
{
    int fx = find(x), fy = find(y);
    if(fx != fy)
    {
        fa[fx] = fy;
        return true;
    }
    return false;
}

int main()
{
    int t;
    scanf("%d", &t);
    while(t--)
    {
        scanf("%d", &n);
        init();
        int edgeCount = 0;//记录边的条数
        for(int i = 1; i <= n; i++)
        {
            for(int j = 1; j <= n; j++)
            {
                int a;
                scanf("%d", &a);
                if(i != j)
                {
                    e[edgeCount].u = i;
                    e[edgeCount].v = j;
                    e[edgeCount].w = a;
                    edgeCount++;
                }
            }
        }
        sort(e, e + edgeCount);
        int longroad = -1;
        int times = 0;//记录选取边的条数
        for(int i = 0; i < edgeCount; i++)
        {
            if(merge(e[i].u, e[i].v))
            {
                longroad = max(longroad, e[i].w);
                if(++times == n - 1)
                    break;
            }
        }
        printf("%d\n", longroad);
    }
    return 0;
}

模板二代码:

int u[maxn], v[maxn], w[maxn];//第i条边的端点序号,权值
int r[maxn];//排序后第i小的边的序号保存在r[i]中【使用了间接排序】

//间接排序:排序关键字是对象的代号,而不是对象本身
bool cmp(int i, int j)
{
    return w[i] < w[j];
}

void init()
{
    for(int i = 0; i <= n; i++)
        fa[i] = i;
    for(int i = 0; i <= m; i++)//初始化边的代号
        r[i] = i;
}

int Find(int x)
{
    return fa[x] == x ? x : fa[x] = Find(fa[x]);
}

void Merge(int x, int y)
{
    int fx = Find(x), fy = Find(y);
    if(fx != fy)
        fa[fx] = fy;
}

int Kruskal()
{
    int ans = 0;
    init();
    sort(r, r + m, cmp);
    for(int i = 0; i < m; i++)
    {
        int e = r[i], uu = u[e], vv = v[e], ww = w[e];
        if(Find(uu) != Find(vv))
        {
            ans += ww;
            Merge(uu, vv);
        }
    }
}

例题二 POJ - 1287 Networking

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条边,两点之间可能有多条边,求最小生成树。

AC代码:

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>

using namespace std;

const int maxn = 1000005;
int fa[55];
int P, R, u[maxn], v[maxn], w[maxn], r[maxn];

bool cmp(int i, int j)
{
    return w[i] < w[j];
}

void init()
{
    for(int i = 0; i <= P; i++)
        fa[i] = i;
    for(int i = 0; i <= R; i++)
        r[i] = i;
}

int Find(int x)
{
    return fa[x] == x ? x : fa[x] = Find(fa[x]);
}

void Merge(int x, int y)
{
    int fx = Find(x), fy = Find(y);
    if(fx != fy)
        fa[fx] = fy;
}

int main()
{
    while(~scanf("%d", &P) && P)
    {
        scanf("%d", &R);
        init();
        for(int i = 0; i < R; i++)
            scanf("%d%d%d", &u[i], &v[i], &w[i]);
        sort(r, r + R, cmp);
        long long ans = 0;
        for(int i = 0; i < R; i++)
        {
            int e = r[i], uu = u[e], vv = v[e], ww = w[e];
            if(Find(uu) != Find(vv))
            {
                ans += ww;
                Merge(uu, vv);
            }
        }
        printf("%lld\n", ans);
    }
    return 0;
}


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值