58pts TLE 求助

P3366 【模板】最小生成树

dctc1494 @ 2024-10-09 11:17:25

在 Bilibili 学了个 Prim,不会优化,有没有大神可以教教我怎么改。

#include <bits/stdc++.h>

using namespace std;
using LL = long long;

const int N = 5e3 + 5;
const int M = 1e5 + 5;
const int INF = 0x3f;

int n, m, u, v, w, res = 0, g[N][N];
vector<int> node;
bool edge[N][N];

int main() {
#ifdef LOCAL
    freopen("in.txt", "r", stdin);
    freopen("out.txt", "w", stdout);
#endif
    ios::sync_with_stdio(false);
    ios_base::sync_with_stdio(false);
    cout.tie(0);
    cin.tie(0);
    cin >> n >> m;
    for (int i = 1; i <= n; ++i) {
        for (int j = 1; j <= n; ++j) {
            if (i == j) {
                g[i][j] = 0;
            } else {
                g[i][j] = INT_MAX;
            }
        }
    }
    for (int i = 1; i <= m; ++i) {
        cin >> u >> v >> w;
        g[u][v] = min(g[u][v], w);
        g[v][u] = min(g[v][u], w);
    }
    for (int i = 1; i <= n; ++i) {
        fill(edge[i] + 1, edge[i] + n + 1, false);
    }
    node.push_back(1);
    for (int k = 2; k <= n; ++k) {
        int mn = INT_MAX;
        pair<int, int> id;
        for (int x : node) {
            for (int i = 1; i <= n; ++i) {
                if (find(node.begin(), node.end(), i) != node.end()) {
                    continue;
                }
                if (g[x][i] < mn) {
                    id = {x, i};
                    mn = g[x][i];
                }
            }
        }
        if (mn == INT_MAX) {
            cout << "orz\n";
            return 0;
        }
        edge[id.first][id.second] = true;
        node.push_back(id.second);
    }
    for (int i = 1; i <= n; ++i) {
        for (int j = 1; j <= n; ++j) {
            if (edge[i][j]) {
                res += g[i][j];
            }
            // cout << edge[i][j] << ' ';
        }
        // cout << '\n';
    }
    cout << res << '\n';

    return 0;
}

by dctc1494 @ 2024-10-09 11:17:56

我完全没有看过任何标准代码。


by Kvj123456 @ 2024-10-22 23:12:07

dctc大蛇应使用 visited 数组来标记已经加入最小生成树的顶点,而不是 node 向量。


|