Submission #1353828

#TimeUsernameProblemLanguageResultExecution timeMemory
1353828i_love_springSirni (COCI17_sirni)C++20
0 / 140
5100 ms281668 KiB
#include <bits/stdc++.h>

using namespace std;

#define ar array
#define ll long long 
const int inf = 2e9;

const int N = 1e7 + 2;
const ll linf = 1e13;

int here[N] = {}, V[N], Z[N];


int find(int x) {
    int y = x;
    while (V[x] > 0) 
        x = V[x];
    while (x != y)
        y = exchange(V[y], x);
    return x;
}

int unite(int x, int y) {
    // cout << x << " " << y << " ";
    x = find(x);
    y = find(y);
    // cout << x << " " << y << " " << Z[x] << " " << Z[y] << "\n";
    if (x == y)
        return 0;
    if (V[x] > V[y])
        swap(x, y);
    V[x] += V[y];
    V[y] = x;
    Z[x] |= Z[y];
    return 1;
}


int good(int x) {
    return Z[find(x)];
}

void solve() {

    // for (int i = 1; i < N;i++)
    //     V[i] = -1, Z[i] = 0;

    int n;
    cin >> n;
    vector<int> A(n);
    vector<ar<int, 3>> edges;
    for (int i = 1; i <= n;i++) {
        int x; cin >> x;
        here[x] = 1;
        A[i - 1] = x;
        Z[x] = 1;
    }   


    sort(A.begin(), A.end());
    A.erase(unique(A.begin(), A.end()), A.end());
    set<int> st;
    for (int i = 1; i < N;i++)
        if (here[i]) 
            for (int d = i; d < N; d += i)
                if (here[d] || st.count(d) == 0) 
                    st.insert(d), unite(i, d); 
    
    for (int x : A) {
        auto it = st.lower_bound(x + 1);
        if (it == st.end())
            continue;
        int y = *it;
        edges.push_back({y - x, x, y});
    }

    ll ans = 0;
    sort(edges.begin(), edges.end());

    for (auto [w, x, y] : edges)
        if (unite(x, y))
            ans += w;

    cout << ans;
}

int32_t main() { 

#ifdef Behruz
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
#endif 

    ios :: sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
    
    solve();

    return 0;
}
#Result Execution timeMemoryGrader output
Fetching results...
#Result Execution timeMemoryGrader output
Fetching results...
#Result Execution timeMemoryGrader output
Fetching results...
#Result Execution timeMemoryGrader output
Fetching results...
#Result Execution timeMemoryGrader output
Fetching results...
#Result Execution timeMemoryGrader output
Fetching results...
#Result Execution timeMemoryGrader output
Fetching results...
#Result Execution timeMemoryGrader output
Fetching results...
#Result Execution timeMemoryGrader output
Fetching results...
#Result Execution timeMemoryGrader output
Fetching results...