Prim16pts求助

P3366 【模板】最小生成树

_awa_keyai @ 2022-10-02 21:21:04

本来码风很清新的,对着第一篇题解改了亿下现在就这样了

#include<bits/stdc++.h>

using namespace std;

inline int read(){
    int ret=0,f=1;
    char c=getchar();
    for(;c<'0'||c>'9';c=getchar()) if(c=='-') f=-f;
    for(;c>='0'&&c<='9';c=getchar()) ret=ret*10+c-'0';
    return ret*f;
}

#define inf 0x3f3f3f3f
#define maxn 5005
#define maxm 200005

struct edge {
    int v,w,next;
} e[maxm<<1];
//无向图两倍数组

int head[maxn],dis[maxn],cnt,n,m,tot,now=1,ans;
bool vis[maxn];

void add(int u,int v,int w) {
    e[++cnt].v=v;
    e[cnt].w=w;
    e[cnt].next=head[u];
    head[u]=cnt;
}

void init() {
    n=read(),m=read();

    for(int i=1,u,v,w; i<=m; i++) {
        u=read(),v=read(),w=read();
        add(u,v,w),add(v,u,w);
    }
}

int prim() {
    for(int i=2; i<=n; i++) {
        dis[i]=inf;
    }

    for(int i=head[1]; i; i=e[i].next) {
        dis[e[i].v]=min(dis[e[i].v],e[i].w);
    }

    while(++tot<n) {
        int minn=inf;
        vis[now]=1;
        for(int i=1; i<=n; i++) {
            if(!vis[i]&&minn>dis[i]) {
                minn=dis[i];
                now=i;
            }
        }
        ans+=minn;
        for(int i=head[now]; i; i=e[i].next) {
            int v=e[i].v;
            if(dis[v]>e[i].w&&!vis[v]) {
                dis[v]=e[i].w;
            }
        }
    }
    return ans;
}

signed main(void) {

    init();

    for(int i=1;i<=n;i++){
        if(!vis[i]){
            printf("orz\n");
            return 0;
        }
    }
    printf("%d\n",prim());

    return 0;
}

by bamboo12345 @ 2022-10-02 21:34:11

@QWQ_lsc_ing 疑惑操作,你这样不全输出orz吗?


by _awa_keyai @ 2022-10-02 21:37:22

@bamboo123 去掉那个疑惑操作,又T又WA /kk.


|