tle求助!

P3366 【模板】最小生成树

_adil_ @ 2023-06-28 09:44:41

无优化prim58pt 几个点tle求调qwq

#include<iostream>
#include<algorithm>
#include<queue>
#include<cstring>
#include<math.h>
#include<set>
#include<vector>
#include<map>
#include<utility>
#include<iomanip>
#define N 1009
#define INF 0x3f3f3f3f
#define mod 998244353
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
const int maxn = 5005;
int a[maxn][maxn], d[maxn], vis[maxn], n,head[maxn],val[maxn],nxt[maxn],to[maxn],cnt;
void add(int x,int y,int z){
    to[++cnt]=y,val[cnt]=z,nxt[cnt]=head[x],head[x]=cnt;
}
void prim()
{
    memset(d, INF, sizeof(d));
    d[1] = 0;
    ll ans=0;
    for(int i=head[1];i;i=nxt[i])
        d[to[i]]=min(d[to[i]],val[i]);
    for(int i = 1; i < n; i++)
    {
        int minn=INF;
        int x = -1;
        for(int j = 1; j <= n; j++)
            if(!vis[j] && d[j]<minn)x = j,minn=d[j];
        if(x!=-1){
            vis[x]=1;
            for(int j=head[x];j;j=nxt[j]){
                int t=to[j];if(!vis[t]&&d[t]>val[j])d[t]=val[j];
            }
        }
    }
    for(int i=1;i<=n;i++)ans+=d[i];
    if(ans>=INF)cout<<"orz"<<endl;else cout<<ans<<endl;
    return ;
}

int main()
{
    int m;
    cin >> n >> m;
    memset(head,-1,sizeof(head));
    for(int i = 1; i <= m; i++)
    {
        int u, v, w;
        cin >> u >> v >> w;
        if(u==v)continue;
        add(u,v,w);
        add(v,u,w);
    }
    prim();
    return 0;
}

by bamboo12345 @ 2023-06-28 09:48:47

@adil 边数组开小了


by _adil_ @ 2023-06-28 11:20:28

@bamboo123 哦确实!谢谢大佬


|