朴素Prim,30分求助(过了最后三个点)

P3366 【模板】最小生成树

_TeaClaudz_ @ 2023-08-15 21:26:49

#include<iostream>
#include<cstring>
using namespace std;

int g[5005][5005], minn[5005];
bool b[5005];

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    int n, m, sum = 0;
    cin >> n >> m;
    for(int i = 1; i <= m; ++i) {
        int x, y, z;
        cin >> x >> y >> z;
        g[x][y] = z;
        g[y][x] = z;
    }
    memset(minn, 0x3f, sizeof(minn));
    minn[1] = 0;
    for(int i = 1; i <= n; ++i) {
        int u = 0;
        for(int j = 1; j <= n; ++j) {
            if(!b[j] && minn[j] < minn[u]) u = j;
        }
        if(u == 0) {
            cout << "orz";
            return 0;
        }
        b[u] = 1;
        sum += minn[u];
        for(int j = 1; j <= n; ++j) {
            if(!b[j] && g[u][j] && g[u][j] < minn[j]) minn[j] = g[u][j];
        }
    }
    cout << sum;
    return 0;
}

by _TeaClaudz_ @ 2023-08-15 21:44:37

重边问题已解决,此贴结


|