【最小生成树】【prim算法(适用于稠密图)】【模板】讲解 + 例题 POJ 2349 Arctic Network【有s个卫星可通信,为使所有城市连通,求最小的最长的边】

最小生成树prim算法过程

  • 随机选取一个点作为初始集合,并保存所有点到这个集合的最短距离。
  • 每次找到离当前集合最近的节点加入这个集合,并更新所有未加入集合的点到这个集合的最短距离。
  • 重复操作直到无新节点可加,连通整个图。

该算法和求最短路的dijkstra算法非常像

//伪代码
设起始点为s
清除所有点的标记
设dis[s] = 0,其他dis[i] = s到i的距离
循环n次
{ 
   在所有未标记的节点中,选出dis值最小的节点X
   给节点X标记
   对于从X出发可以到达的,且不在当前集合中的点y,更新dis[y] = min{dis[y],w(x,y)}//只有此处与dijkstra算法不同,dijkstra为:对于从X出发可以到达的点y,更新dis[y] = min{dis[y], dis[x]+w(x,y)}
}

朴素法(邻接矩阵建图) 复杂度O(n^2)

int n, m, ans;
int vis[maxn], mapp[maxn][maxn], dis[maxn]; //dis记录未被加入集合的点到集合的最短距离

int prim(int s)
{
    //mapp中不通的路为INF
    memset(vis, 0, sizeof(vis));
    ans = 0;
    for(int i = 1; i <= n; i++) 
        dis[i] = mapp[s][i]; //随便选择一个点s,dis记录所有点到s的距离
    dis[s] = 0; //自己到自己距离为0
    vis[s] = 1; //标记为访问过
    for(int i = 1; i < n; i++) //第一个点已经加入集合,还有n-1个点
    {
        int mi = INF, id;//记录不在集合里的所有点到当前集合的最近距离
        for(int j = 1; j <= n; j++) //选择到集合距离最短的点,更新最短距离并记录该点
        {
            if(!vis[j] && dis[j] < mi) 
            {
                mi = dis[j];
                id = j;
            }
        }
        if(mi == INF)
        {
            ans = -1;    //mi为无穷大表明没有与该图连通的点,也就是说这个图不是完全图
            return;
        }
        ans += mi;
        vis[id] = 1; //将与该集合距离最短的点标记为访问过
        for(int j = 1; j <= n; j++) //更新不在集合中的各点 与 加入新点后的集合  的最近距离
        {
            if(!vis[j]) 
                dis[j] = min(dis[j], mapp[id][j]);
        }
    }
    return ans;
}

优先队列法(堆优化) O(mlogn)

int vis[maxn], mapp[maxn][maxn], n, m, dis[maxn];

//写法一所需数据结构
struct Edge
{
    int from, to, dist;
    Edge(int u, int v, int d): from(u), to(v), dist(d) {};
};

vector<Edge> edges;
vector<int> G[maxn];

void init(int n)
{
    for(int i = 0; i < n; i++)
        G[i].clear();
    edges.clear();
}

void addedge(int from, int to, int dist)
{
    edges.push_back(Edge(from, to, dist));
    m = edges.size();
    G[from].push_back(m - 1);
}
//写法一end

struct node
{
    int v, len; //v表示当前节点,len表示该点到已经连通集合的最短距离
    friend bool operator < (node a, node b)
    {
        return a.len > b.len;
    }
};


int prim(int s)
{
    int ans = 0;
    priority_queue<node> q;
    memset(dis, INF, sizeof(dis));
    memset(vis, 0, sizeof(vis));
    node beg;
    beg.v = s;
    beg.len = 0;
    q.push(beg);
    while(!q.empty())
    {
        node cur = q.top();
        q.pop();
        if(vis[cur.v])
            continue;
        vis[cur.v] = 1;
        ans += cur.len;
        //写法一:用edges存图
        for(int i = 0; i < G[cur.v].size(); i++)
        {
            Edge e = edges[G[cur.v][i]];
            if(!vis[e.to] && dis[e.to] > e.dist)
            {
                node next;
                next.v = e.to;
                next.len = e.dist;
                dis[e.to] = e.dist;
                q.push(next);
            }
        }//写法一end
        //写法二:用数组存图
        for(int i = 1; i <= n; i++)
        {
            if(!vis[i] && dis[i] > mapp[i][cur.v])
            {
                node next;
                next.v = i;
                next.len = mapp[i][cur.v];
                dis[i] = mapp[i][cur.v];
                q.push(next);
            }
        }//写法二end
    }
    return ans;
}

例题:POJ 2349 Arctic Network

Description
The Department of National Defence (DND) wishes to connect several northern outposts by a wireless network. Two different communication technologies are to be used in establishing the network: every outpost will have a radio transceiver and some outposts will in addition have a satellite channel.
Any two outposts with a satellite channel can communicate via the satellite, regardless of their location. Otherwise, two outposts can communicate by radio only if the distance between them does not exceed D, which depends of the power of the transceivers. Higher power yields higher D but costs more. Due to purchasing and maintenance considerations, the transceivers at the outposts must be identical; that is, the value of D is the same for every pair of outposts.

Your job is to determine the minimum D required for the transceivers. There must be at least one communication path (direct or indirect) between every pair of outposts.

Input
The first line of input contains N, the number of test cases. The first line of each test case contains 1 <= S <= 100, the number of satellite channels, and S < P <= 500, the number of outposts. P lines follow, giving the (x,y) coordinates of each outpost in km (coordinates are integers between 0 and 10,000).

Output
For each case, output should consist of a single line giving the minimum D required to connect the network. Output should be specified to 2 decimal points.

Sample Input
1
2 4
0 100
0 300
0 600
150 750

Sample Output
212.13

【中文题目】
Description
国防部(DND)要用无线网络连接北部几个哨所。两种不同的通信技术被用于建立网络:每一个哨所有一个无线电收发器,一些哨所将有一个卫星频道。

任何两个有卫星信道的哨所可以通过卫星进行通信,而不管他们的位置。同时,当两个哨所之间的距离不超过D时可以通过无线电通讯,D取决于对收发器的功率。功率越大,D也越大,但成本更高。出于采购和维修的方便,所有哨所的收发器必须是相同的;那就是说,D值对每一个哨所相同。

你的任务是确定收发器的D的最小值。每对哨所间至少要有一条通信线路(直接或间接)。

Input
输入的第一行是测试数据的数量N。
每组测试数据的第一行包含卫星频道的数量S(1 < = S < = 100)和哨所的数量P(S < P < = 500)。接下来的P行,给出以公里为单位的每个哨所的坐标(x,y)( 坐标为0到10000之间的整数)。

Output
对于每组测试数据,输出一行,输出收发器的D的最小值。精确到小数点后两位。

题意:
有两种不同的通信技术,有卫星通信的两个城市之间可以任意联络,但用无线电通信的城市只能和距离不超过D的城市联系。无线电的能力越高(即传输距离D越大),花费就越大。已知无线电的数目m,要所有城市可以连通,求最小的D。

思路:
先求出所有顶点间的距离(稠密图)。用prim算出最小生成树,可以得到n个dis(n-1条边,还有一个为0), 因为有s个卫星可以通信,可以节省s - 1条边,那么选择最长的s-1条边,所求的D即第S大的边。

AC代码:

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

using namespace std;

const int maxn = 505;
const double INF = 0x3f3f3f3f3f3f3f3f;
double dis[maxn], mapp[maxn][maxn];
int vis[maxn], n, s;

struct point
{
    double x, y;
}p[maxn];

double length(int i, int j)
{
    double x = p[i].x - p[j].x;
    double y = p[i].y - p[j].y;
    double l = sqrt(x * x + y * y);
    return l;
}

void prim(int s)
{
    memset(vis, 0, sizeof(vis));
    for(int i = 0; i < n; i++)
    {
        dis[i] = mapp[s][i];
    }
    dis[s] = 0;
    vis[s] = 1;
    for(int i = 0; i < n - 1; i++)
    {
        int id;
        double mi = INF;
        for(int j = 0; j < n; j++)
        {
            if(!vis[j] && dis[j] < mi)
            {
                mi = dis[j];
                id = j;
            }
        }
        vis[id] = 1;
        for(int j = 0; j < n; j++)
        {
            if(!vis[j])
                dis[j] = min(dis[j], mapp[id][j]);
        }
    }
}

int main()
{
    int t;
    scanf("%d", &t);
    while(t--)
    {
        scanf("%d%d", &s, &n);
        for(int i = 0; i < n; i++)
        {
            scanf("%lf%lf", &p[i].x, &p[i].y);
        }
        for(int i = 0; i < n; i++)
        {
            for(int j = i + 1; j < n; j++)
                mapp[i][j] = mapp[j][i] = length(i, j);
            mapp[i][i] = INF;
        }
        prim(0);
        sort(dis, dis + n);
        printf("%.2f\n", dis[n - s]);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Floraqiu/article/details/81459484