Prim全re求助,本地没问题

P3366 【模板】最小生成树

FallacyMaker @ 2021-12-09 22:27:02

rt

#include <bits/stdc++.h>
#define rep(i,a,n,k) for(int i=a;i<=n;i+=k)
#define per(i,a,n,k) for(int i=n;i>=a;i-=k)
#define pb push_back
#define mp make_pair
#define all(x) (x).begin(),(x).end()
#define fi first
#define se second
#define il inline
#define SZ(x) ((int)(x).size())
using namespace std;
typedef vector<int> VI;
typedef pair<int, int> PII;
typedef long long ll;
typedef double db;
const int INF = 0x7fffffff;
const int inf = 0x3f3f3f3f;
const int MOD = 998244353;
const int mod = 1e9 + 7;
ll gcd(ll a, ll b) { return b ? gcd(b, a % b) : a; }
// head
template<typename T>
inline void scan(T& x) {
    x = 0; int f = 1; char ch = getchar();
    if (ch == '-') f = -f;
    else x = (x << 3) + (x << 1) + ch - 48;
    while ((ch = getchar()) >= '0' && ch <= '9')
        x = (x << 3) + (x << 1) + ch - 48;
    x *= f;
}
//-----------------------------
const int N = 5010;
const int M = 400010;
int n, m, cnt, tot, ans;
int d[N], h[N], to[M], nxt[M], val[M];
bitset<N>vis;
priority_queue<PII, vector<PII>, greater<PII> >q;
void add(int u, int v, int w) { to[++tot] = v, val[tot] = w, nxt[tot] = h[u]; h[u] = tot; }
int main() {
    // freopen("a.in","r",stdin);
    vis.reset(); scan(n), scan(m);
    rep(i, 1, m, 1) { int u, v, w; scan(u), scan(v), scan(w); add(u, v, w); add(v, u, w); }
    rep(i, 2, n, 1) { d[i] = INF; } vis[1] = 1;
    q.push(mp(0, 1));
    while (!q.empty() && cnt < n) {
        int w = q.top().fi, ver = q.top().se; q.pop();
        for (int i = h[ver]; i; i = nxt[i]) {
            if (vis[to[i]] == 0 && d[to[i]] > val[i]) {
                d[to[i]] = val[i];
                q.push(mp(val[i], to[i]));
            }
        }
        if (vis[ver] == 0) {
            vis[ver] = 1; cnt++; ans += d[ver];
        }
    }
    rep(i, 1, n, 1) if (vis[i] == 0) { puts("orz"); return 0; }
    cout << ans << '\n';
    return 0;
}

by FallacyMaker @ 2021-12-10 13:32:58

破案了,scan的快读有template,寄了


|