84求调

P3366 【模板】最小生成树

liyishao1125 @ 2024-01-24 09:49:00

错#13

#include<bits/stdc++.h>
using namespace std;
const int N=5001;
const int INF=0x3f3f3f3f3f3f;
bool vis[N];
int n,m,dis[N],g[N][N];
int prim(int s){
    int sum=0,cnt=0;
    memset(vis,0,sizeof(vis));
    memset(dis,0x3f,sizeof(dis));
    dis[s]=0;
    for(int i=1;i<=n;i++){
        int u,minn=INF;
        for(int j=1;j<=n;j++){
            if(!vis[j]&&minn>dis[j]){
                minn=dis[j];
                u=j;
            }
        }
        cnt++;
        vis[u]=1;
        sum+=minn;
        for(int v=1;v<=n;v++){
            if(!vis[v]&&dis[v]>g[u][v]){
                dis[v]=g[u][v];
            }
        }
    }
    if(cnt<n)sum=-1;
    return sum;
}
int main(){
    cin>>n>>m;
    for(int i=1;i<=n;i++){
        for(int j=1;j<=n;j++){
            g[i][j]=INF;
            if(i==j)g[i][j]=0;
        }
    }
    int u,v,w;
    for(int i=1;i<=m;i++){
        cin>>u>>v>>w;
        if(g[u][v]>w){
            g[u][v]=w;
            g[v][u]=w;
        }
    }
    int ans=prim(1);
    if(ans==-1)cout<<"orz\n";
    else cout<<ans<<"\n";
}

by OldDriverTree @ 2024-01-24 09:59:07

@liyishao1125 你这无解的情况判了跟没判断好像没有区别啊(跑完 prim 后 cnt 一定 == n 啊(


by liyishao1125 @ 2024-01-24 10:03:08

@OldDriverTree 感谢 已AC


|