Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- #define fs first
- #define sc second
- #define mp make_pair
- #define pb emplace_back
- #define sz(s) ((int) s.size ())
- #define all(s) s.begin (), s.end ()
- using namespace std;
- typedef long long ll;
- typedef pair<int, int> ii;
- typedef unsigned long long ull;
- const ll linf = (ll) 1e18;
- const int pw = 997;
- const int N = 100009;
- const int M = 10000000;
- const int inf = (int) 1e9;
- const int mod = (int) 1e9 + 7;
- const double eps = 1e-10;
- const double pi = 3.1415926535897932384626433832795;
- int a[N];
- int p[M + 9];
- int r[M + 9];
- bool e[M + 9];
- int get (int v) {
- return v == p[v] ? v : p[v] = get (p[v]);
- }
- bool unite (int a, int b) {
- a = get (a);
- b = get (b);
- if (a != b) {
- if (r[a] < r[b]) {
- swap (a, b);
- }
- p[b] = a;
- if (r[a] == r[b]) {
- r[a]++;
- }
- return 1;
- }
- return 0;
- }
- inline void prepare () {
- }
- inline void solve () {
- int n; scanf ("%d", &n);
- int mn = +M;
- int mx = -M;
- for (int i = 0; i < n; i++) {
- scanf ("%d", &a[i]);
- e[a[i]] = 1;
- p[a[i]] = a[i];
- mn = min (mn, a[i]);
- mx = max (mx, a[i]);
- }
- sort (a, a + n);
- n = unique (a, a + n) - a;
- if (n == 1) {
- puts ("0");
- return;
- }
- if (n <= 10000) {
- vector<bool> used (n);
- vector<int> min_e (n, inf), sel_e (n, -1);
- min_e[0] = 0;
- ll ans = 0;
- for (int i = 0; i < n; i++) {
- int v = -1;
- for (int j = 0; j < n; j++) {
- if (!used[j] && (v == -1 || min_e[j] < min_e[v])) {
- v = j;
- }
- }
- used[v] = true;
- ans += min_e[v];
- for (int to = 0; to < n; to++) {
- int now = min (a[v] % a[to], a[to] % a[v]);
- if (now < min_e[to]) {
- min_e[to] = now;
- sel_e[to] = v;
- }
- }
- }
- printf ("%lld", ans);
- return;
- }
- ll ans = 0;
- int cmp = n;
- for (int r = 0; r < mn; r++) {
- for (int i = 0; i < n; i++) {
- for (int j = a[i]; j <= mx; j += a[i]) {
- if (e[j + r]) {
- bool u = unite (a[i], j + r);
- if (u) {
- cmp--;
- ans += r;
- if (cmp == 1) {
- printf ("%lld", ans);
- return;
- }
- }
- }
- }
- }
- }
- }
- int main () {
- #ifdef FSTREAM
- #define name ""
- freopen (name".in", "r", stdin);
- freopen (name".out", "w", stdout);
- #endif // FSTREAM
- int tests = 1;
- prepare ();
- while (tests--) {
- solve ();
- }
- }
Add Comment
Please, Sign In to add comment