Triple#12369

Triple (Editorial)

Problem Author:

Andriy Kholod (Connect)

Prepared by:

Andriy Kholod (Connect)

Analysis:

Andriy Kholod (Connect)

Idea

At the second stage, we can only compress subarrays into their sum. This means that the final array [x,x,x] always corresponds to some partition of the initial array into three non-empty contiguous parts with equal sums.

That is, after all replacements in the first stage, the array must become such that there exist indices 1 \le i < j < n and the following holds:

\sum_{k=1}^{i} a_k = \sum_{k=i+1}^{j} a_k = \sum_{k=j+1}^{n} a_k

Thus, the problem is actually: change the minimum number of elements so that the array can be partitioned into three non-empty subarrays with equal sums.

Why the answer is not greater than 2

You can always change no more than two elements.

Indeed, take any partition into three non-empty parts, for example: { {a_1}, {a_2}, {a_3,\dots,a_n} } Then you can change one element in the first part and one element in the second part so that the sums of all three parts become equal.

Therefore, the answer is always one of: [ 0,\ 1,\ 2 ]

Thus, it is sufficient to learn to check:

  • whether the answer is ;

  • whether the answer is ;

  • otherwise, the answer is .

Case of 0 changes

Let S = \sum_{i=1}^{n} a_i

If we do not change any elements, then the array must already be partitionable into three parts with equal sum. Thus, it must hold: S \equiv 0 \pmod 3 and each part must have a sum x = S/3

This can be checked very simply using prefix sums:

  • look for a prefix with sum ;

  • then look for a prefix with sum further to the right.

If both exist such that the third part is non-empty, then the answer is .

When one change is sufficient

Let us say we want to change exactly one element. Then after this change, the array must be partitioned into three parts with equal sums.

Key observation: if only one element is changed, it lies in exactly one of the three parts. Thus, the other two parts must already have equal sums. We can "pull" the third part to this value with one change.

Therefore, we need to check if there exists a partition into three non-empty parts where the sums of two parts are already equal.

Let the second cut be after position , where 2 \le j < n Then the three parts are: { {1..i},\ {i+1..j},\ {j+1..n} } for some i < j.

Consider three cases of equality of two parts.

1) The first and second parts are equal

Then: \text{pref}[i] = \text{pref}[j] - \text{pref}[i] that is, 2 \cdot \text{pref}[i] = \text{pref}[j] or \text{pref}[i] = \frac{\text{pref}[j]}{2}

Thus, for a fixed , it is sufficient to know whether the prefix has been seen before and whether is even.

2) The second and third parts are equal

Then: \text{pref}[j] - \text{pref}[i] = S - \text{pref}[j] From this: \text{pref}[i] = 2 \cdot \text{pref}[j] - S

Thus, we need to check if such a prefix existed before.

3) The first and third parts are equal

Then: \text{pref}[i] = S - \text{pref}[j]

That is, it is also sufficient to check whether such a prefix existed before.

Why these checks are sufficient

For each , we consider all possible i < j implicitly through the set of already seen prefix sums.

The set seen contains all values: \text{pref}[1], \text{pref}[2], \dots, \text{pref}[j-1]

Thus, each of the three conditions above in answers the question:

  • whether there exists such an that the first and second parts are equal;

  • whether there exists such an that the second and third parts are equal;

  • whether there exists such an that the first and third parts are equal.

If at least one of these conditions holds, then the two parts already have equal sums, and the third can be corrected with one replacement.

Thus, the answer is .

Why the iteration goes exactly for j = 2 \dots n-1

We want all three parts to be non-empty:

  • the first part must contain at least one element \Rightarrow i \ge 1;

  • the second part must be non-empty \Rightarrow i < j;

  • the third part must be non-empty \Rightarrow j < n.

Therefore, the outer loop goes over 2 \le j < n and before the check, \text{pref}[j-1] is added to seen to ensure that index is definitely less than .

Final Algorithm

For each test case:

  1. Calculate prefix sums.

  2. Check if it is possible to immediately obtain three equal sums without changes. If so, the answer is .

  3. Otherwise, iterate over the second boundary and check the three conditions for one change using the set of prefixes. If at least one holds, the answer is .

  4. Otherwise, the answer is .

Correctness

We have already proven:

  • if there exists a partition into three equal sums without changes, the code will output ;

  • if this is not possible, but there exists a partition where two parts already have equal sums, the code will find it and output ;

  • if neither nor is suitable, then it is always possible to achieve the answer with changes.

Thus, the algorithm always finds the minimum number of changes.

Asymptotics

For each test case:

  • calculating prefix sums — ;

  • checking case — ;

  • checking case using unordered_set — on average.

Thus, the total complexity: per test on average, and across all tests: O\left(\sum n\right)

Memory:

Solution Code

#include <bits/stdc++.h>
#include <random>
// fast_pragmas

//#pragma GCC optimize("O3")
//#pragma GCC optimize("Ofast")
//#pragma GCC optimize ("unroll-loops")
//#pragma GCC target("avx,avx2,tune=native")

// fast_pragmas ended

//#pragma comment(linker, "/stack:200000000")
//#pragma GCC optimize("Ofast")
//#pragma GCC optimize("O3,unroll-loops")
//#pragma GCC target("sse,sse2,sse3,ssse3,sse4")
//#pragma GCC target("avx2,bmi,bmi2,popcnt,lzcnt")

using namespace std;

#define ull unsigned long long
#define ll long long
#define ld long double
#define speed ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define endl '\n'
#define yes cout<<"YES"<<endl
#define no cout<<"NO"<<endl
#define pb push_back
#define ln log
#define lg log10
#define log log2
#define here cout<<"HERE"<<endl

const ll clasik = 5e5 + 7;
const ll mln = 1e6 + 7;
const ll mod = 1e9 + 7;
//const ll mod = 998244353;
const ll block_size = 450;
const ll INF = 1e17;

ll df[clasik];

void solve() {
    ll n;
    cin >> n;

    vector<ll> a(n + 1), pref(n + 1, 0);

    for (int i = 1; i <= n; i++) {
        cin >> a[i];
        pref[i] = pref[i - 1] + a[i];
    }

    ll S = pref[n];

    bool zero = false;

    if (S % 3 == 0) {
        ll x = S / 3;
        bool first_found = false;

        for (int i = 1; i < n; i++) {
            if (pref[i] == x) first_found = true;
            if (pref[i] == 2 * x && first_found) {
                zero = true;
                break;
            }
        }
    }

    if (zero) {
        cout << 0 << endl;
        return;
    }

    bool one = false;
    unordered_set<ll> seen;
    seen.reserve(n * 2);

    for (int j = 2; j < n; j++) {
        seen.insert(pref[j - 1]);

        if (pref[j] % 2 == 0 && seen.count(pref[j] / 2)) {
            one = true;
            break;
        }

        if (seen.count(2 * pref[j] - S)) {
            one = true;
            break;
        }

        if (seen.count(S - pref[j])) {
            one = true;
            break;
        }
    }

    if (one) cout << 1 << endl;
    else cout << 2 << endl;
}

signed main() {

    //freopen("deciding_points_input.txt" , "r" , stdin);
    //freopen("outputA.txt" , "w" , stdout);

    speed;
    int test;
    test = 1;
    //precalc();
    cin >> test;
    for (int tt = 1; tt <= test; tt++) {
        //cout << "Case #" << tt << ": ";
        solve();
    }

    return 0;
}