动态数组加结构体省空间,重载结构体排序写队列优先级。
#include<iostream>
#include<queue>
#include<vector>
using namespace std;
int n,m;
int vis[5001];
struct edge{
int v,w;
};
vector<edge> G[5001];
struct node{
int id,d;
};
struct cmp{
bool operator()(node x,node y){
return x.d>y.d;//按d从小到大排序,与sort自定义规则相反
}
};
void prim(){
priority_queue<node,vector<node>,cmp > Q;
Q.push((node){1,0});
int ans = 0;
int cnt = 0;
while(Q.size()){
node t = Q.top();
Q.pop();
int u = t.id;
int d = t.d;
if(vis[u]==1) continue;
vis[u]=1;
ans += d;
cnt++;
for(int i=0;i<G[u].size();i++){
int v = G[u][i].v;
int w = G[u][i].w;
if(vis[v]==1) continue;
Q.push((node){v,w});
}
}
if(cnt==n) cout<<ans;
else cout<<"orz";
}
int main(){
cin>>n>>m;
for(int i=1;i<=m;i++){
int u,v,w;
cin>>u>>v>>w;
G[u].push_back((edge){v,w});
G[v].push_back((edge){u,w});
}
prim();
return 0;
}