跳到正文

题解

题解 P3366 【【模板】最小生成树】

dph754132771约 3 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月20日
篇幅
约 3 分钟
题目
P3366

版本

  1. v1当前

/* * p3366

* Au:Small_Ash

* 裸的最小生成树。。。

* prim和克鲁斯卡尔任你选

* 因为楼上的都是克鲁斯卡尔,我就发一份prim的吧

* 但是要劝各位,还是学一下邻接表再来用prim,因为用邻接矩阵的话,非简单图(即有重边)就会炸(我WA了8次才发现。。。)

* 大概思路就是每次找一头在已搜索点集的另一头在未搜索点集的最小边,然后加入

* 由于每次都是找最小边,所以可以用堆来加快运算。。。

* 上代码:

*/

C++
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <functional>//优先队列关键库
#include <queue>//同上
using namespace std;
struct number{
    int x,i;
    bool operator < (const number &a) const {
        return x>a.x;//最小值优先,因为默认是大根堆的说。。。
    }
}A,B;//中转站而已
priority_queue <number> q;//堆
int map[5005][5005],n,m,a,b,c,ans;
bool v[5005];
int main(){
    memset(v,false,sizeof(v));
    memset(map,-1,sizeof(map));
    scanf("%d%d",&n,&m);
    for (int i=0;i<m;i++){
        scanf("%d%d%d",&a,&b,&c);
        if (map[a][b]==-1||c<map[a][b]) map[a][b]=c;
        if (map[b][a]==-1||c<map[b][a]) map[b][a]=c;
    }
    v[1]=true;
    for (int i=1;i<=n;i++)
        if (map[1][i]!=-1){
            A.x=map[1][i];
            A.i=i;
            q.push(A);
        }
    for (int i=1;i<n;i++){
        if (q.empty()){
            printf("orz");
            return 0;
        }
        B=q.top();
        q.pop();
        while (v[B.i]){
            B=q.top();
            q.pop();
            if (q.empty()){
                printf("orz");
                return 0;
            }
        }
        ans+=B.x;
        v[B.i]=true;
        for (int j=1;j<=n;j++)
        if (map[B.i][j]!=-1&&!v[j]){
            A.x=map[B.i][j];
            A.i=j;
            q.push(A);
        }
    }
    printf("%d",ans);
    return 0;
}
原文