제출 #1353988

#제출 시각아이디문제언어결과실행 시간메모리
1353988i_love_springSirni (COCI17_sirni)C++20
140 / 140
4347 ms512184 KiB
#include <bits/stdc++.h>

using namespace std;

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

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

int here[N] = {}, V[N], nxt[N];
vector<int> A;
vector<ar<int, 3>> edges;



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) {
    x = find(x);
    y = find(y);
    if (x == y)
        return 0;
    if (V[x] > V[y])
        swap(x, y);
    V[x] += V[y];
    V[y] = x;
    return 1;
}


void solve() {

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

    int n;
    cin >> n;
    
    A.reserve(n);

    for (int i = 1; i <= n;i++) {
        int x; cin >> x;
        here[x] = 1;
        A.push_back(x);
    }   


    sort(A.begin(), A.end());
    A.erase(unique(A.begin(), A.end()), A.end());
    
    for (int i = A.back() - 1; i > 0; i--) {
        nxt[i] = nxt[i + 1];
        if (here[i + 1])
            nxt[i] = i + 1;
    }


    for (int x : A) {
        for (int d = x; d < N; d += x) {
            if (here[d])
                unite(d, x);
            if (nxt[d] == -1)
                continue;
            if (d + x < N && nxt[d] == nxt[d + x])
                continue;
            int y = nxt[d];
            edges.push_back({y - d, x, y});
        }
    }



    sort(edges.begin(), edges.end());
    ll ans = 0;
    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;
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...