/ SeriousOJ /

Record Detail

Wrong Answer


  
# Status Time Cost Memory Cost
#1 Accepted 1ms 328.0 KiB
#2 Accepted 4ms 576.0 KiB
#3 Wrong Answer 1ms 532.0 KiB
#4 Accepted 1ms 532.0 KiB
#5 Wrong Answer 1ms 532.0 KiB

Code

#include <bits/stdc++.h>
using namespace std;

using ll = long long;

const int MAXN = 200005;
const int MAXK = 25;

int N;
ll X;
ll A[MAXN];

// divisors[X + k]
vector<ll> divisors[MAXK];

// cost[i][k]: cost to make A[i] gcd > 1 with X + k
ll cost[MAXN][MAXK];


// trial division up to sqrt(X)
void factorize(ll Y, vector<ll> &D) {
    D.clear();
    for (ll d = 1; d * d <= Y; ++d) {
        if (Y % d == 0) {
            if (d > 1) D.push_back(d);
            if (Y / d != d && Y / d > 1) D.push_back(Y / d);
        }
    }
}

ll get_cost(ll a, const vector<ll> &D) {
    ll best = LLONG_MAX;
    for (ll d : D) {
        ll add = (d - (a % d)) % d;
        best = min(best, add);
    }
    return best;
}

ll sum_cost(int l, int r, int k) {
    ll res = 0;
    for (int i = l; i <= r; ++i) {
        if (cost[i][k] == LLONG_MAX) return LLONG_MAX;
        res += cost[i][k];
    }
    return res;
}


ll solve(int l, int r, int k) {
    if (k >= MAXK) return LLONG_MAX;
    if (l == r) return cost[l][k];

    int m = (l + r) / 2;

    ll left = solve(l, m, k + 1);
    ll right_gcd = sum_cost(m + 1, r, k);

    ll right = solve(m + 1, r, k + 1);
    ll left_gcd = sum_cost(l, m, k);

    ll ans1 = LLONG_MAX, ans2 = LLONG_MAX;
    if (left != LLONG_MAX && right_gcd != LLONG_MAX) ans1 = left + right_gcd;
    if (right != LLONG_MAX && left_gcd != LLONG_MAX) ans2 = right + left_gcd;

    return min(ans1, ans2);
}



int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);

    cin >> N >> X;
    for (int i = 0; i < N; ++i) {
        cin >> A[i];
    }

    for (int k = 0; k < MAXK; ++k) {
        ll Y = X + k;
        factorize(Y, divisors[k]);
    }

    for (int i = 0; i < N; ++i) {
        for (int k = 0; k < MAXK; ++k) {
            cost[i][k] = get_cost(A[i], divisors[k]);
        }
    }


    ll ans = solve(0, N - 1, 0);
    if (ans >= LLONG_MAX / 2) cout << -1 << '\n';
    else cout << ans << '\n';

    return 0;
}

Information

Submit By
Type
Submission
Problem
P1168 F. x ordinary array
Language
C++17 (G++ 13.2.0)
Submit At
2025-07-15 09:22:29
Judged At
2025-07-15 09:22:29
Judged By
Score
3
Total Time
4ms
Peak Memory
576.0 KiB