Prim模版
2025-09-29 17:35:33
发布于:上海
1阅读
0回复
0点赞
#include<iostream>
#include<vector>
#include<queue>
#define ll long long
using namespace std;
struct node{
int u;
ll dis;
bool operator>(const node o) const{
return dis > o.dis;
}
};
priority_queue<node,vector<node>,greater<node>> q;
vector<vector<node>> mp;
vector<bool> vis;
int n,m,x,y,cnt = 0;
ll z,ans = 0;
int main(){
cin >> n >> m;
mp.resize(n + 5),vis.resize(n + 5,0);
while(m--){
cin >> x >> y >> z;
mp[x].push_back({y,z}),mp[y].push_back({x,z});
}
q.push({1,0});
while(!q.empty()){
int r = q.top().u,d = q.top().dis;
q.pop();
if(vis[r]) continue;
vis[r] = 1;
cnt++,ans += d;
for(auto next : mp[r]){
if(!vis[next.u]) q.push(next);
}
}
if(cnt == n) cout << ans;
else cout << "orz";
return 0;
}
这里空空如也
有帮助,赞一个