PHSHFT - Editorial

PROBLEM LINK:

Practice
Contest: Division 1
Contest: Division 2
Contest: Division 3
Contest: Division 4

Author: nikhil_010309
Tester: raysh07
Editorialist: iceknight1093

DIFFICULTY:

TBD

PREREQUISITES:

Prefix sums

PROBLEM:

You have a binary string S.
You can choose an index i such that S_{i-1} \ne S_{i+1}, and flip S_i. This has a cost of C_i.

Find the lexicographically maximum binary string you can reach within a budget of B.

EXPLANATION:

Let’s define D_i = S_i \oplus S_{i+1} to be the difference between adjacent characters of the string.
(Recall that we’re assuming S_0 = S_{N+1} = 0, so D_0 and D_N are well-defined.)

Observe that the condition S_{i-1} \ne S_{i+1} is equivalent to D_{i-1} \ne D_i.
Further, flipping S_i flips both D_{i-1} and D_i, which is equivalent to swapping them.

So, on D, we can swap adjacent elements when they aren’t equal - which is really the same as being able to swap adjacent elements period since there’s no point swapping equal elements when we’re on a budget.

Now, note that the number of ones in D cannot be changed - but we can move them around.
Further, the string S is determined exactly by the positions of the ones in D, as follows:

  • Suppose the ones in D are at positions x_1, x_2, \ldots, x_k
  • Then, S will have:
    • Zeros till position x_1 - 1.
    • Ones from position x_1 to position x_2-1.
    • Zeros from position x_2 to position x_3-1.
    • And so on.

Basically, the ones in D denote the positions where maximal blocks of equal values in S start.


With this in mind, to lexicographically maximize S we see that we want:

  • x_1 to be as small as possible (to have a 1 as early as possible)
  • x_2 to be as large as possible (to extend the first block of ones as long as we can)
  • x_3 to be as small as possible (again, to start the next block of ones early)
    \vdots

In general, we want the odd-indexed x_i to be minimized, while the even-indexed ones must be maximized.
Of course, this must be done while maintaining x_1 \lt x_2 \lt\ldots\lt x_k at all times.

Let’s now attempt to do this greedily.

Moving x_1 as far left as possible is easy - we know the cost of each movement, so simply repeat that as much as needed (or possible.)
Moving x_2 right is a bit harder - because when doing this, we might end up having to push some other values of x_i to the right in the meantime.

One way to implement this nicely, is to group the x_i into contiguous blocks when they occupy contiguous positions.
Then, when attempting to move a point right, if it’s attached to a block we instead attempt to move the entire block right; because this is the only way to move this point one step.
The cost of this move is a subarray sum over C and can be computed using prefix sums.

Finally, whenever we are unable to move right further, we simply fix the leftmost element of the block in place, and then detach it from the current block so that the block can move by itself later on.

This simple-looking optimization in fact gives us a linear-time algorithm!

To see why:

  • The total number of leftward moves is bounded by N, even making them one at a time.
    • This is because if some x_i crosses a position moving left, then x_{i+1} must be to the right of that position - and will remain to its right.
    • Thus, no other x_j for j \gt i will ever touch this position again.
  • Similarly, the total number of rightward moves is bounded by N, because after moving a block rightwards from a position we’ll never touch it with a rightward move ever again.

So, with proper implementation this gives a simple linear-time algorithm!


There are other solutions as well, where using some prefix sums and binary search you can find all the necessary costs quickly enough; though that’s a bit lengthier to implement and likely more error-prone compared to the method above.
Nonetheless, such an implementation is attached below for reference.

TIME COMPLEXITY:

\mathcal{O}(N) or \mathcal{O}(N\log N) per testcase.

CODE:

Tester's code (C++, Nlog N)
#include <bits/stdc++.h>
using namespace std;
#define int long long
#define INF (int)1e18

mt19937_64 RNG(chrono::steady_clock::now().time_since_epoch().count());

void Solve() 
{
    // for an array (a1, ..., ak) number of 0s before each 1 and (b1, .., bk), cost is sum |ai - bi| 
    // for a partial array, k 0s placed, upto i fixed
    
    int n, budget; cin >> n >> budget;
    string s; cin >> s;
    s = "0" + s + "0";
    
    vector <int> c(n + 1);
    for (int i = 1; i <= n; i++){
        cin >> c[i];
    }
    
    vector <int> t;
    for (int i = 1; i <= n + 1; i++){
        t.push_back((int)(s[i] != s[i - 1]));
    }
    
    vector <int> b;
    int curr = 0;
    for (auto x : t){
        if (x == 0){
            curr++;
        } else {
            b.push_back(curr);
        }
    }
    
    if (b.size() == 0){
        for (int i = 1; i <= n; i++){
            cout << "0";
        }
        cout << "\n";
        return;
    }
    
    int lst = 0;
    string ans = "";
    vector <int> d;
    int lim = 0;
    int base = 0;
    
    vector <int> pc(n + 1);
    for (int i = 1; i <= n; i++){
        pc[i] = pc[i - 1] + c[i];
    }
    
    vector <int> ppc(n + 1), pcb(n + 1);
    for (int i = 1; i <= n; i++){
        ppc[i] = ppc[i - 1] + pc[i];
    }
    for (int i = 0; i < b.size(); i++){
        pcb[i] = pc[b[i] + i];
        if (i > 0) pcb[i] += pcb[i - 1];
    }
    
    auto f = [&](int zero1, int zero2, int ind){
        // go to 1-indexed
        int pos1 = zero1 + ind + 1;
        int pos2 = zero2 + ind + 1;
        
        // need to go from pos1 to pos2 
        if (pos1 > pos2) swap(pos1, pos2);
        
        return pc[pos2 - 1] - pc[pos1 - 1];
    };
    
    auto check = [&](){
        int sz = d.size();
        if (sz > (int)b.size()) return false;
        if (lim > ((int)t.size() - (int)b.size())) return false;
        
        int cost = base;
        // for (int i = sz; i < b.size(); i++){
        //     if (b[i] > lim) continue; // 0 cost 
        //     cost += f(lim, b[i], i);
        // }
        
        int lo = sz, hi = (int)b.size();
        while (lo != hi){
            int mid = (lo + hi) / 2;
            if (b[mid] > lim){
                hi = mid;
            } else {
                lo = mid + 1;
            }
        }
        
        // i = [sz, lo) 
        // in this range, we want pc[lim + i - 1] - pc[b[i] + i - 1]
        // for (int i = sz; i < lo; i++){
        //     cost += pc[lim + i] - pc[b[i] + i];
        // }
        
        auto get_sum = [&](vector <int> &a, int l, int r){
            if (l == 0){
                return a[r];
            } else {
                return a[r] - a[l - 1];
            }
        };
        
        cost += get_sum(ppc, lim + sz, lim + lo - 1);
        cost -= get_sum(pcb, sz, lo - 1);
        
        return cost <= budget;
    };
    
    auto add0 = [&](){
        lim++;
    };
    
    auto add1 = [&](){
        d.push_back(lim);
        if (d.size() <= b.size()){
            int sz = d.size();
            base += f(d[sz - 1], b[sz - 1], sz - 1);
        }
    };
    
    auto rem0 = [&](){
        lim--;
    };  
    
    auto rem1 = [&](){
        if (d.size() <= b.size()){
            int sz = d.size();
            base -= f(d[sz - 1], b[sz - 1], sz - 1);
        }
        d.pop_back();
    };
    
    for (int i = 1; i <= n; i++){
        if (lst == 0){
            // try to make 1 work 
            add1();
            if (!check()){
                rem1();
                add0();
                ans += "0";
                lst = 0;
            } else {
                ans += "1";
                lst = 1;
            }
        } else {
            // try to make 0 work 
            add0();
            if (!check()){
                rem0();
                add1();
                ans += "0";
                lst = 0;
            } else {
                ans += "1";
                lst = 1;
            }
        }
    }
    
    cout << ans << "\n";
}

int32_t main() 
{
    auto begin = std::chrono::high_resolution_clock::now();
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    int t = 1;
    // freopen("in",  "r", stdin);
    // freopen("out", "w", stdout);
    
    cin >> t;
    for(int i = 1; i <= t; i++) 
    {
        //cout << "Case #" << i << ": ";
        Solve();
    }
    auto end = std::chrono::high_resolution_clock::now();
    auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(end - begin);
    cerr << "Time measured: " << elapsed.count() * 1e-9 << " seconds.\n"; 
    return 0;
}