Official

D - Make Geometric Sequence Editorial by en_translator


Any geometric sequence with common ratio greater than \(1\) can be made a geometric sequence with common ratio less than \(1\).

Therefore, it is sufficient to determine if one can obtain a geometric sequence with common ratio less than or equal to \(1\).

First, we determine if the absolute value of the common ratio is \(1\). When \(r=1\), the values in the sequence are all equal. When \(r=-1\), there exists an integer \(x\) such that the sequence consists of \(\lceil N/2\rceil\) copies of \(x\) and \(\lfloor N/2\rfloor\) copies of \(-x\). One can check these criteria in \(O(N)\) time.

If a sequence is a geometric sequence with common ratio less than \(1\), the absolute values of the elements decrease monotonically, so it is sufficient to sort \(A\) by the absolute values and check if the resulting sequence is a geometric sequence.

The following is sample code.

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    using namespace std;
    unsigned T;
    cin >> T;
    for (unsigned t{}; t < T; ++t) cout << ([]{
        unsigned N;
        cin >> N;
        vector<long> A(N);
        for (auto&& a : A)
            cin >> a;

        // Print Yes if the values are all equal
        if (ranges::count(A, A[0]) == N)
            return true;

        // Print Yes if the sequence contains the initial value and its negation
        if (const auto p_cnt{ranges::count(A, A[0])}, n_cnt{ranges::count(A, -A[0])}; p_cnt + n_cnt == N && min(p_cnt, n_cnt) == N / 2)
            return true;

        // Sort by absolute values
        ranges::sort(A, greater{}, [](const auto a){ return abs(a); });

        // If the absolute value of the common ratio is 1, then it must form a geometric progression when sorted by absolute values
        for (unsigned i{}; i + 2 < N; ++i)
            if (A[i] * A[i + 2] != A[i + 1] * A[i + 1])
                return false;
        return true;
    }() ? "Yes" : "No") << endl;
    return 0;
}

posted:
last update: