最小生成树:洛谷P3366【模板】最小生成树

https://www.luogu.com.cn/problem/P3366

Prim算法/最小生成树裸题:不断取出未加入集合的点中距离最近的那个,并将其连的所有边加入priority_queue中(priority_queue重载运算符<然后用node),反复循环直到priority_queue为空

重点:priority_queue的使用

#include<bits/stdc++.h>
#define INF 2147483647
using namespace std;
int been[5003];
struct node{
    int num,to,value;
};
bool operator < (const node &a, const node &b){
    return a.value > b.value;
} 
int main(){
    vector<node>a[5003];
    priority_queue<node> q;
    int n,m,i,x,y,z,ans,ansn;
    node t;t.value=INF;
    memset(been,0,sizeof(been));
    cin>>n>>m;
    for(i=1;i<=m;i++){
        scanf("%d%d%d",&x,&y,&z);
        node b,c;
        b.num=x;b.to=y;b.value=z;
        c.num=y;c.to=x;c.value=z;
        if(z<t.value) t=b;
        a[x].push_back(b);
        a[y].push_back(c);
    }
    t.to=t.num;t.value=0;q.push(t);
    ans=0;ansn=0;
    while(!q.empty()){
        node b=q.top();q.pop();x=b.to;
        if(been[x]) continue;
        ans+=b.value;ansn++;
        been[x]=true;
//        printf("%d->%d:%d\n",b.num,b.to,b.value);
        for(i=0;i<a[x].size();i++){
            if(!been[a[x][i].to]) q.push(a[x][i]);
        }    
    }
    if(ansn==n) cout<<ans; else cout<<"orz";
} 

 

上一篇:Maven相关问题


下一篇:echarts图表报错‘SyntaxError: Identifier ‘data‘ has already been declared’