This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <iostream>
#include <vector>
#include <set>
#include <algorithm>
#include <tuple>
#include <queue>
using namespace std;
using ll = long long;
int n;
vector<int> parent, sizes;
int cc;
void init() {
parent.resize(n);
sizes.resize(n);
cc = n;
for (int i = 0; i < n; i++) {
parent[i] = i;
sizes[i] = 1;
}
}
int find_set(int a) {
if (parent[a] == a) {
return a;
}
return parent[a] = find_set(parent[a]);
}
void join_set(int a, int b) {
a = find_set(a);
b = find_set(b);
if (a == b) {
return;
}
if (sizes[a] > sizes[b]) {
swap(a, b);
}
cc--;
parent[a] = b;
sizes[b] += sizes[a];
}
int main() {
cin >> n;
set<int> q;
int mp = 0;
for (int i = 0; i < n; i++) {
int x;
cin >> x;
q.insert(x);
mp = max(mp, x);
}
vector<int> p;
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
int cur = 0;
vector<vector<int>> mults(n);
for (int c : q) {
p.push_back(c);
while (pq.size()) {
int fr = pq.top().first;
int x = pq.top().second;
if (fr <= c) {
pq.pop();
mults[x].push_back(cur);
}
else {
break;
}
}
mults[cur].push_back(0);
mults[cur].push_back(0);
for (int i = 2 * c; i <= mp; i += c) {
pq.push(make_pair(i, cur));
}
cur++;
}
n = p.size();
// Kruskal's Algorithm for MST
vector<tuple<int, int, int>> edges;
// It is optimal to go from c to lower_bound(ck) and then from ck to ck+m
for (int j = 0; j < n; j++) {
int c = p[j];
if (j != n - 1) {
edges.push_back(make_tuple(p[j + 1] % c, j, j + 1));
}
for (int i = 2; i <= mp / c; i ++) {
edges.push_back(make_tuple(p[mults[j][i]] % c, j, mults[j][i]));
}
}
sort(edges.begin(), edges.end());
ll ans = 0;
init();
for (auto c : edges) {
ll w, a, b;
tie(w, a, b) = c;
if (find_set(a) == find_set(b)) {
continue;
}
join_set(a, b);
ans += w;
if (cc == 1) {
break;
}
}
cout << ans << endl;
return 0;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |