prim.

858. Prim算法求最小生成树

给定一个 nn 个点 mm 条边的无向图,图中可能存在重边和自环,边权可能为负数。

求最小生成树的树边权重之和,如果最小生成树不存在则输出 impossible

给定一张边带权的无向图 G=(V,E)G=(V,E),其中 VV 表示图中点的集合,EE 表示图中边的集合,n=|V|n=|V|,m=|E|m=|E|。

由 VV 中的全部 nn 个顶点和 EE 中 n−1n−1 条边构成的无向连通子图被称为 GG 的一棵生成树,其中边的权值之和最小的生成树被称为无向图 GG 的最小生成树。

输入格式

第一行包含两个整数 nn 和 mm。

接下来 mm 行,每行包含三个整数 u,v,wu,v,w,表示点 uu 和点 vv 之间存在一条权值为 ww 的边。

输出格式

共一行,若存在最小生成树,则输出一个整数,表示最小生成树的树边权重之和,如果最小生成树不存在则输出 impossible

数据范围

1≤n≤5001≤n≤500,
1≤m≤1051≤m≤105,
图中涉及边的边权的绝对值均不超过 1000010000。

输入样例:
4 5
1 2 1
1 3 2
1 4 3
2 3 2
3 4 4
输出样例:
6
#include <cstring>
#include <iostream>
#include <algorithm>

using namespace std;

const int N = 510, INF = 0x3f3f3f3f;

int n, m;
int g[N][N];
int dist[N];
bool st[N];
int prim()
{
    memset(dist,0x3f,sizeof(dist));
    int res=0;
    for(int i=0;i<n;i++)
    {
        int t=-1;
        for(int j=1;j<=n;j++)
        {
            if(!st[j]&&(t==-1||dist[t]>dist[j]))
            {
                t=j;
            }
        }
        st[t]=true;
        if(i&&dist[t]==INF )    return INF;
        if(i)   res+=dist[t];
        for(int j=1;j<=n;j++)   dist[j]=min(dist[j],g[t][j]);
    }
   
    return  res;
}

int main()
{
    cin>>n>>m;
    memset(g,0x3f,sizeof(g));
    while(m--)
    {
        int u,v,w;
        cin>>u>>v>>w;
        g[u][v]=g[v][u]=min(g[u][v],w);
    }
    int t=prim();
    if(t==INF)   puts("impossible");
    else cout<<t;
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Prim's algorithm, also known as the Prim's minimum spanning tree (MST) algorithm, is a widely used graph theory method for finding the minimum spanning tree of a connected weighted graph. It's named after computer scientist Robert C. Prim. Here's an explanation: 1. **基本思想**:Prim's algorithm starts with an arbitrary vertex (or node) and then iteratively adds the next closest edge from the unvisited nodes to the growing tree while ensuring that the total weight of the tree remains minimum. 2. **操作流程**: - 初始化:选择一个顶点(通常是任意一个或具有最小权重的边)作为树的起点,并标记为已访问。 - 更新:在剩余的未访问节点中,查找与当前树中某个节点相连且权重最小的边,将这条边所连接的节点加入到树中,并更新当前树的总权重。 - 重复:重复此过程,直到所有节点都被访问过,或者无法再添加边而树不再扩大。 3. **数据结构使用**:通常使用优先队列(如斐波那契堆)来高效地找到下一个最优边缘,因为这样可以在常数时间内进行插入和删除操作。 4. **复杂度分析**:Prim's algorithm has a time complexity of O(E log V), where E is the number of edges and V is the number of vertices, due to the priority queue operation. 5. **应用领域**:Prim's algorithm finds practical applications in network design, transportation planning, and even recommendation systems where you want to find the most efficient way to connect a group of entities with minimal cost.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值