题解(prim版)
2026-11-21 15:14:40
发布于:广东
3阅读
0回复
0点赞
因为本题的数据太大所以是优化版prim,加了链式前向星和优先队列
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
typedef pair<int,int> PLL;
const int N=1e5+5,M=1e6+5;
int n,m,vis[N],d[N];
int h[N],ne[M],e[M],w[M],idx;
void add(int a,int b,int c){
e[idx]=b;
w[idx]=c;
ne[idx]=h[a];
h[a]=idx++;
}
void prim(){
memset(d,0x3f,sizeof d);
priority_queue<PLL,vector<PLL>,greater<PLL> > que;
que.push({0,1});
d[1]=0;
while(que.size()){
int t=que.top().second;
que.pop();
vis[t]=1;
for(int j=h[t];j!=-1;j=ne[j]){
int y=e[j];
if(vis[y]==0){
if(w[j]<d[y]){
d[y]=w[j];
que.push({w[j],y});
}
}
}
}
}
int main(){
memset(h,-1,sizeof h);
cin>>n>>m;
for(int i=1;i<=m;i++){
int x,y,z;
cin>>x>>y>>z;
add(x,y,z);
add(y,x,z);
}
prim();
long long ans=0;
for(int i=1;i<=n;i++){
ans+=d[i];
if(d[i]==0x3f3f3f3f){
cout<<"orz";
return 0;
}
}
cout<<ans;
return 0;
}
全部评论 1
不不不,这无疑是“有用”的!

2天前 来自 广东
0













有帮助,赞一个