79分堆优化prim求助大佬

P3366 【模板】最小生成树

Dark_lightrq @ 2022-08-29 18:12:44

8,9,10TLE

#include<bits/stdc++.h>
#define IL inline
using namespace std;
int n,m;
const int N=5005,M=2e5+5;
int head[N],nxt[M],ver[M],w[M],tot;
IL void add(int x,int y,int z){
    ver[++tot]=y,nxt[tot]=head[x],head[x]=tot,w[tot]=z;
}
priority_queue<pair<int,int> >q;
bool v[N];
int d[N];
int main(){
    scanf("%d%d",&n,&m);
    for(int i=1;i<=m;i++){
        int x,y,z;
        scanf("%d%d%d",&x,&y,&z);
        add(x,y,z);
        add(y,x,z);
    }
    for(int i=1;i<=n;i++)d[i]=1000000000;
    d[1]=0;
    q.push(make_pair(0,1));
    int cnt=0;
    int ans=0;
    while(q.size()&&cnt<n){
        int x=q.top().second;
        q.pop();
        if(v[x])continue;
        v[x]=1;
        cnt++;
        ans+=d[x];
        for(int i=head[x];i;i=nxt[i]){
            int y=ver[i],z=w[i];
            if(d[y]>z){
                d[y]=z;
                q.push(make_pair(-d[y],y));
            }
        }
    }
    if(cnt==n)cout<<ans;
    else cout<<"orz";
    return 0;
}

by bamboo12345 @ 2022-08-29 18:17:27

怎么跑出来竟然比 O(n^2) 还更劣呢


by bamboo12345 @ 2022-08-29 18:20:42

@Dark_lightrq 边的数组开小了,要开两倍


by Dark_lightrq @ 2022-08-29 18:26:59

@bamboo123 AC了,谢谢大佬


|