RE求调玄一关

P3366 【模板】最小生成树

jy20091121 @ 2024-05-07 18:54:49

#include<bits/stdc++.h>
using namespace std;
int g[3322][3132];
bool f[2321302];
int dis[2132032];
int n,m;
int res;
int prim(){
    memset(dis,0x3f,sizeof dis);
    for(int i=0;i<n;i++){
        int t=-1;
        for(int j=1;j<=n;j++){
            if(!f[j]&&(t==-1||dis[j]<dis[t])) t=j;
        }
        if(i!=0&&dis[t]==0x3f3f3f3f) return 0x3f3f3f3f;
        if(i!=0) res+=dis[t];
        for(int j=1;j<=n;j++) dis[j]=min(dis[j],g[t][j]);
        f[t]=1;
    }
}
int main(){
    cin>>n>>m;
    memset(g,0x3f,sizeof g);
    for(int i=1;i<=m;i++){
        int x,y,z;
        cin>>x>>y>>z;
        g[x][y]=g[y][x]=min(g[x][y],z);
    }
    int l=prim();
    if(l==0x3f3f3f3f) cout<<"orz";
    else cout<<res;
    return 0;
}

by yudongkai1234 @ 2024-05-07 19:16:40

orz


by DBL_MAX @ 2024-06-10 15:07:40

@zhangjiayii

#include <bits/stdc++.h>
using namespace std;
#define N 10005
#define M 10000005

struct Edge {
    int u, v, w;
} edge[M];
int s[N];

int find_set(int x) {
    if (x != s[x])
        s[x] = find_set(s[x]);
    return s[x];
}

bool EdgeCmp(Edge a, Edge b) {
    return a.w < b.w;
}
int n, m;

void kruskal() {
    sort(edge + 1, edge + 1 + m, EdgeCmp);
    for (int i = 1; i <= n; i++)
        s[i] = i;
    int ans = 0, cnt = 0;
    for (int i = 1; i <= m; i++) {
        if (n - 1 == cnt)
            break;
        int e1 = find_set(edge[i].u);
        int e2 = find_set(edge[i].v);
        if (e1 == e2)
            continue;
        else {
            ans += edge[i].w;
            s[e1] = e2;
            cnt++;
        }
    }
    if (n - 1 == cnt)
        cout << ans;
    else
        cout << "orz";
}

int main() {
    cin >> n >> m;
    for (int i = 1; i <= m; i++)
        cin >> edge[i].u >> edge[i].v >> edge[i].w;
    kruskal();
    return 0;
}

|