最小生成树学习记录
xiaogougou_11 · · 个人记录
#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;
}