跳到正文

个人记录

最小生成树学习记录

xiaogougou_11约 3 分钟
原文
文章信息与版本

文章信息

发布
2026年8月13日
收录
2026年8月19日
更新
2026年11月14日
篇幅
约 3 分钟

版本

  1. v1当前
C++
#include<bits/stdc++.h>
using namespace std;
const int N = 505;
int n, m;
int value[N];
int fa[N];
struct Edge {
    int u, v;    
    long long w; 
    bool operator < (const Edge& other) const {
        return w > other.w; 
    }
};
vector<Edge> edges;
long long qpow(long long a, long long b, long long mod) {
    long long res = 1;
    a %= mod;
    while (b) {
        if (b & 1) res = res * a % mod;
        a = a * a % mod;
        b >>= 1;
    }
    return res;
}
int root(int x) {
    return fa[x] == x ? x : fa[x] = root(fa[x]);
}
int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cin >> n >> m;
    for (int i = 1; i <= n; i++) {
        fa[i] = i;
        cin >> value[i];
    }
    for (int i = 1; i <= n; i++) {
        for (int j = i + 1; j <= n; j++) {
            long long w = (qpow(value[i], value[j], m) + qpow(value[j], value[i], m)) % m;
            edges.push_back({i, j, w}); 
        }
	}
    sort(edges.begin(), edges.end());
    long long ans = 0;
    int cnt = 0;
    for (auto t : edges) {
        int x = root(t.u);
        int y = root(t.v);
        if (x != y) {
            fa[x] = y;
            ans += t.w;
            cnt++;
            if (cnt == n - 1) break;
        }
    }
    cout << ans;
    return 0;
}
原文