最小生成树Prim&Kruskal算法

题目链接:1258—Agri-Net

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
Source

USACO 102


1.prim算法

#include <set>
#include <queue>
#include <vector>
#include <iostream>
#include <algorithm> 
using namespace std;
const int MAXN = 110;
const int INF = 0x3f3f3f3f; //初始化为最大值 
int cost[MAXN][MAXN];	
bool visited[MAXN];	//顶点是否已经进入S集合 
int mincost[MAXN]; 	//从集合S到未被选中集合的最小权值 
int n;	//顶点数 
int Prim(){
	for(int i=0; i<n; i++){
		mincost[i] = INF;
		visited[i] = false;
	}
	//从0开始prim算法 
	mincost[0] = 0;
	int res = 0;
	while(true){
		int v = -1;
		for(int i=0; i<n; i++){
			//从当前集合到未被选中集合 找一条权值最小的边 
			if(!visited[i]&&(v==-1||mincost[i]<mincost[v])){
				v = i;
			}
		} 
		if(v==-1)break;
		visited[v] = true;
		res += mincost[v];
		//更新权值,有Dijskra的意思 
		for(int i=0; i<n; i++){
			mincost[i] = min(mincost[i],cost[v][i]);
		}
	}
	return res;
}
int main(){
	while(cin>>n){
		for(int i=0; i<n; i++){
			for(int j=0; j<n; j++){
				cin>>cost[i][j];
			}
		}
		cout<<Prim()<<endl;
	}
    return 0;
}

2.Kruskal算法

#include <set>
#include <queue>
#include <vector>
#include <iostream>
#include <algorithm> 
using namespace std;
const int MAXN = 110;
struct edge{
	//边的起点顶点、终点顶点、边的权值 
	int u, v, w;
};
edge e[MAXN];	//结构体边数组 
int n; // 顶点数


int f[MAXN];	//并查集父节点数组 

//重载结构体数组,按边权从小到大排序 
bool cmp(const edge& a, const edge& b){
	return a.w < b.w;
} 
//并查集 ---- 用于判断两条边是否连接的定点同属一个集合 
void init(){
	for(int i=1; i<=n; i++)
		f[i] = i;
} 
int find(int i){
	if(f[i]!=i){
		f[i] = find(f[i]);
	}
	return f[i];
}

bool merge(int a, int b){
	a = find(a);
	b = find(b);
	if(a != b){
		f[a] = b;
		return true;
	}else{
		return false;
	}
}
int Kruskal(int edgenum){
	init();
	int cur_edgenum = 0;
	int res = 0;
	sort(e, e+edgenum, cmp);
	for(int i=0; i<edgenum; i++){
		//加入的边不能使树产生回路 
		if(merge(e[i].u, e[i].v)){
			res += e[i].w;
			//边数 等于 顶点数 - 1 算法结束 
			if(++cur_edgenum == n-1){
				return res;
			}
		}
	}
	return cur_edgenum;
}
int main(){
	int i, j, cost;
	cin>>n;
	int edgenum = 0; //边数 
	for(i=1; i<=n; i++){
		for(j=1; j<=n; j++){
			cin>>cost;			
			//屏蔽题目中的权为0的自环 
			if(i != j){	
				e[edgenum].u = i;
				e[edgenum].v = j;
				e[edgenum++].w = cost; 
			}
		}
	}
	cout << Kruskal(edgenum) << endl;
    return 0;
}

两种求最小生成树算法的比较:

算法时间复杂度使用
primO(n2)(n为图的顶点数)适合稠密图
kruskalO(eloge)(e为图的边数目)适合稀疏图

补一道题

1584. 连接所有点的最小费用

给你一个points 数组,表示 2D 平面上的一些点,其中 points[i] = [xi, yi]

连接点 [xi, yi] 和点 [xj, yj] 的费用为它们之间的 曼哈顿距离|xi- xj| + |yi - yj| ,其中 |val| 表示 val 的绝对值。

请你返回将所有点连接的最小总费用。只有任意两点之间 有且仅有 一条简单路径时,才认为所有点都已连接。

示例 1:

在这里插入图片描述

输入:points = [[0,0],[2,2],[3,10],[5,2],[7,0]]
输出:20
解释:

我们可以按照上图所示连接所有点得到最小总费用,总费用为 20 。
注意到任意两个点之间只有唯一一条路径互相到达。

示例 2:

输入:points = [[3,12],[-2,5],[-4,1]]
输出:18

示例 3:

输入:points = [[0,0],[1,1],[1,0],[-1,1]]
输出:4

示例 4:

输入:points = [[-1000000,-1000000],[1000000,1000000]]
输出:4000000

示例 5:

输入:points = [[0,0]]
输出:0

提示:

  • 1 <= points.length <= 1000
  • -106 <= xi, yi <= 106
  • 所有点 (xi, yi) 两两不同。

Kruskal算法:

class Solution { 
public:
    typedef struct edge{
        int a, b, w; 
        edge(int s,int p,int c):a(s),b(p),w(c){}
        bool operator <(const edge& g){return w < g.w;}
    }e;
    int Find(int n){
        if(f[n]==n) return n;
        f[n]=Find(f[n]);
        return f[n];
    }
    vector<int> f;
    vector<e> edges;
    int minCostConnectPoints(vector<vector<int>>& points) {
        for(int i=0;i<points.size();i++) f.push_back(i);
        int n = points.size();  
        for(int i = 0; i < n-1; i++){
            for(int j = i+1; j < n; j++){
               edges.push_back(edge(i,j,abs(points[i][0]-points[j][0])+abs(points[i][1]-points[j][1])));
            }
        }
        sort(edges.begin(), edges.end());
        /*
        for(auto x : edges){
            cout << x.a <<" " << x.b <<" " << x.w <<endl;
        }*/
        int ans = 0, cnt = 0;
        for(int i = 0; i < edges.size(); i++){
            int p1 = edges[i].a, p2 = edges[i].b;
            int r1 = Find(p1), r2 = Find(p2);
            if(r1 != r2){
                //cout << p1 << " " << p2 << " " << edges[i].w <<endl;
                ans += edges[i].w;
                f[r1] = r2;
                cnt++;
            }
            if(cnt == n-1) break;
        }
        return ans;
    }
};

Prim

class Solution {
public:
    int prim(int n, vector<vector<int>>& nums) {
		vector<int> dis(n, INT_MAX);
        dis[0] = 0;
        int ans = 0;
        int from = 0;
        vector<bool> isVisited(n, false);
        //逐次添加 n 个结点
        for(int i = 0; i < n; i ++){
            int minDis = INT_MAX;
            //找出未访问过的最近结点
            for(int i = 0; i < n; i ++){
                if(!isVisited[i] && dis[i] < minDis){
                    minDis = dis[i];
                    from = i;
                }
            }
            //标记为访问过
            isVisited[from] = true;
            ans += dis[from];
            //更新其他结点的距离
            for(int i = 0; i < n; i ++){
                if(!isVisited[i] && nums[from][i] < dis[i]){
                    dis[i] = nums[from][i];
                }
            }
        }
        return ans;
    }

    int minCostConnectPoints(vector<vector<int>>& points) {
        int n = points.size();
        if(n <= 1) return 0;
        vector<vector<int>> nums(n, vector<int>(n, 0));//记录两个点之间的权重
        for(int i = 0; i < n; i ++){
            for(int j = 0; j < n; j ++){
                int dis = abs(points[i][0] - points[j][0]) + abs(points[i][1] - points[j][1]); 
                nums[i][j] = dis;
            }
        }
        return prim(n, nums);
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Prim算法Kruskal算法都是用于求解最小生成树的经典算法Prim算法的基本思想是从一个点开始,每次选择一个与当前生成树距离最近的点加入生成树中,直到所有点都被加入生成树为止。具体实现时,可以使用一个优先队列来维护当前生成树与未加入生成树的点之间的距离,每次选择距离最小的点加入生成树中。 Kruskal算法的基本思想是从边开始,每次选择一条权值最小且不会形成环的边加入生成树中,直到生成树中包含所有点为止。具体实现时,可以使用并查集来判断是否形成环。 下面是Prim算法Kruskal算法的C语言代码实现: Prim算法: ```c #include <stdio.h> #include <stdlib.h> #include <limits.h> #define MAX_VERTICES 1000 int graph[MAX_VERTICES][MAX_VERTICES]; int visited[MAX_VERTICES]; int dist[MAX_VERTICES]; int prim(int n) { int i, j, u, min_dist, min_index, sum = 0; for (i = 0; i < n; i++) { visited[i] = 0; dist[i] = INT_MAX; } dist[0] = 0; for (i = 0; i < n; i++) { min_dist = INT_MAX; for (j = 0; j < n; j++) { if (!visited[j] && dist[j] < min_dist) { min_dist = dist[j]; min_index = j; } } u = min_index; visited[u] = 1; sum += dist[u]; for (j = 0; j < n; j++) { if (!visited[j] && graph[u][j] < dist[j]) { dist[j] = graph[u][j]; } } } return sum; } int main() { int n, m, i, j, u, v, w; scanf("%d%d", &n, &m); for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { graph[i][j] = INT_MAX; } } for (i = 0; i < m; i++) { scanf("%d%d%d", &u, &v, &w); graph[u][v] = graph[v][u] = w; } printf("%d\n", prim(n)); return 0; } ``` Kruskal算法: ```c #include <stdio.h> #include <stdlib.h> #include <limits.h> #define MAX_VERTICES 1000 #define MAX_EDGES 1000000 struct edge { int u, v, w; }; int parent[MAX_VERTICES]; struct edge edges[MAX_EDGES]; int cmp(const void *a, const void *b) { return ((struct edge *)a)->w - ((struct edge *)b)->w; } int find(int x) { if (parent[x] == x) { return x; } return parent[x] = find(parent[x]); } void union_set(int x, int y) { parent[find(x)] = find(y); } int kruskal(int n, int m) { int i, sum = 0; for (i = 0; i < n; i++) { parent[i] = i; } qsort(edges, m, sizeof(struct edge), cmp); for (i = 0; i < m; i++) { if (find(edges[i].u) != find(edges[i].v)) { union_set(edges[i].u, edges[i].v); sum += edges[i].w; } } return sum; } int main() { int n, m, i; scanf("%d%d", &n, &m); for (i = 0; i < m; i++) { scanf("%d%d%d", &edges[i].u, &edges[i].v, &edges[i].w); } printf("%d\n", kruskal(n, m)); return 0; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值