None_Po's blog

By None_Po, history, 8 months ago, In English

Problem:

Given an array A of size N

We need to partition it into non-overlapping subarrays (continuous segments)

For each segment: MEX = smallest non-negative integer not present

Score = sum of MEX of all segments

Goal: Maximize total score

example

  1. a= 0,2,1,1 ans= 3 (we can divide it into {0,2,1},{1} whose MEX are 3 and 0 respectively)

2.a= 0,2,1,1,0 ans= 5 (we can divide it into {0,2,1},{1,0} whose MEX are 3 and 2 respectively)

What I tried-

  1. DP, 1 state, but it had a for loop inside it that was running from i to n. O(n^2). This caused TLE ofcourse.
  2. DP, same as above, but I called rec() it whenever I encountered 0;
   mex=0;
   for(i to n)
      keeping mex updated
      if(arr[i]==0)
          ans=max(ans, mex+rec(i))

   return max(ans,mex)

This ran few cases for the dry run, but for hidden cases it wasn't running. the reason i thought of calling rec() because the partition need an element 0 for MEX to calculate

  1. greedy, but was couldn't find the right approach/ direction for greedy. I was again cutting whenever i was finding 0 but wasn't good solution.

Doubt:

  • Is there a correct greedy strategy?
  • Or is there a way to optimize DP?
  • What observation am I missing?

Thanks.

  • Vote: I like it
  • +13
  • Vote: I do not like it

»
8 months ago, hide # |
 
Vote: I like it 0 Vote: I do not like it

Auto comment: topic has been updated by None_Po (previous revision, new revision, compare).

»
8 months ago, hide # |
 
Vote: I like it 0 Vote: I do not like it

Auto comment: topic has been updated by None_Po (previous revision, new revision, compare).

»
8 months ago, hide # |
← Rev. 2  
Vote: I like it 0 Vote: I do not like it

@None_Po please provide the problem link

  • »
    »
    8 months ago, hide # ^ |
     
    Vote: I like it 0 Vote: I do not like it

    This question was asked in a test, so i dont have it.

    The test ended and it was on hackerearth and was set up by my college.

    So dont have.

»
8 months ago, hide # |
← Rev. 8  
Vote: I like it 0 Vote: I do not like it

Let’s take your example: 0, 2, 1, 1, 0 For the full array we know the MEX 3. Now suppose we maintain a count like cnt[] = {2, 2, 1, 0, 0, …}. If you remove all occurrences of a value v such that v < MEX, then the MEX becomes v itself.

So, by removing values from left to right, you can determine the MEX of the remaining (right-side) array and for the left side, you can just add values one by onea DSU-based approach should work Or, you can apply the same process in reverse and store the values.

So, both O(n) and O(n log n) approaches are possible.

I misunderstood the question at first, I thought only need to divide the array into 2 subarrays. so

Update: From every zero, we will take the MEX before the next zero. Now, if there are x zeros, we have x blocks. Iterate from the back and decide whether it’s better to merge two adjacent blocks or not. Now merge if (old MEX1 + old MEX2) < new merged MEX.
Also, if you have a link to the problem, please share it, I’d like to give it a try.

  • »
    »
    8 months ago, hide # ^ |
     
    Vote: I like it 0 Vote: I do not like it

    i did try the 0 one, like u said.

    i tried DP, my 2nd approach is similar to what u said in update.

    sorry, dont have the link. This question was asked in a test, so i dont have it. The test ended and it was on hackerearth and was set up by my college.

  • »
    »
    8 months ago, hide # ^ |
     
    Vote: I like it 0 Vote: I do not like it

    If there are x zeros, we have ≤ x blocks. For test [5,4,3,2,0,0,1] for 1 block answer is 6, while for 2 blocks is 3

»
6 months ago, hide # |
 
Vote: I like it 0 Vote: I do not like it

My assumption is

dp[i] considering some partition ending at r = i, the most optional l for that subarray partition is opt[i] = l

my whole assumption is that opt array is a sorted array, i'm not that much sure, but i think opt array should be non-decreasing, if this is true, we can use two pointer to make the transition amortized O(n), and mex inside last subarray can be maintained using a set

if i'm incorrect, someone correct me

»
5 months ago, hide # |
← Rev. 4  
Vote: I like it 0 Vote: I do not like it

Here's how I did it. Think it's worst case O(nlogn), average case O(n)? Not sure but it behaves linear on every type of input I could think of. Wanna explain it more later in a blog post or smth.

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

struct boundary {
    int L, l, r, R;
    int mex;

    boundary(int _L, int _l, int _r, int _R, int _mex) :
        L(_L), l(_l),
        r(_r), R(_R),
        mex(_mex)
    {};

    boundary() {};

    friend ostream& operator<<(ostream &os, const boundary &b) {
        return os << "[" << b.L << ", " << b.l << ") x [" << b.r << ", " << b.R << ") - " << b.mex;
    };
};

struct treap_node; using treap_node_ptr = treap_node*;
struct treap_node {
    int idx, val;
    treap_node_ptr p = nullptr, l = nullptr, r = nullptr;
    boundary* bound = nullptr;
    bool left = false, del = false;

    treap_node(int _idx, int _val) :
        idx(_idx), val(_val)
    {};

    void left_rotate() {
        treap_node_ptr y = this->r;

        this->r = y->l;
        if (y->l) y->l->p = this;
        y->p = this->p;

        (this == this->p->l ? this->p->l : this->p->r) = y;
        y->l = this;
        this->p = y;
    };

    void right_rotate() {
        treap_node_ptr y = this->l;

        this->l = y->r;
        if (y->r) y->r->p = this;
        y->p = this->p;

        (this == this->p->l ? this->p->l : this->p->r) = y;
        y->r = this;
        this->p = y;
    };

    treap_node_ptr remove() {
        treap_node_ptr c = (this->l ? this->l : this->r);
        (this == this->p->l ? this->p->l : this->p->r) = c;
        if (c) c->p = this->p;

        delete this;
        return nullptr;
    };
};

class mex_treap {
private:
    int n;
    treap_node_ptr root, right;
    vector<treap_node_ptr> val_to_node;
    vector<treap_node_ptr> stack;
    vector<boundary> bounds;

    treap_node_ptr get(treap_node_ptr x) {
        if (!x || (!x->del)) return x;

        stack.push_back(x);
        while (!stack.empty()) {
            x = stack.back(); stack.pop_back();
            
            bool push_l = (x->l && x->l->del), push_r = (x->r && x->r->del);
            if (push_l || push_r) {
                stack.push_back(x);
                if (push_r) stack.push_back(x->r);
                if (push_l) stack.push_back(x->l);
            }
            else {
                if (!(x->l || x->r)) x = x->remove();
                else {
                    if (!x->l || (x->r && x->r->val <= x->l->val)) x->left_rotate();
                    else x->right_rotate();
                    treap_node_ptr p = x->p;
                    if (!(x->l && x->r)) x->remove();
                    x = p;
                }
            }
        }

        return x;
    };

    void app(int idx, int val) {
        treap_node_ptr
            x = new treap_node(idx, val),
            u = this->right->p,
            v = this->right;
        
        while (!(v = get(v)) || x->val < v->val) u = (v = u)->p;

        x->l = v->r;
        if (v->r) v->r->p = x;
        v->r = x;
        x->p = v;

        this->right = x;
        val_to_node[val] = x;
        x->left = (v == this->root);
    };

public:
    mex_treap(int _n) :
        n(_n),
        val_to_node(_n + 1, nullptr) {
            stack.reserve(2*n + 5);
            bounds.reserve(2*n + 5);
            this->right = this->root = new treap_node(-1, INT_MIN);
            for (int i = 0; i <= n; i++) app(-1, i);
    };

    pair<boundary*, vector<boundary*>> adv(int idx, int val) {
        this->root->idx++;
    
        pair<boundary*, vector<boundary*>> ret = {nullptr, {}};
        if (!(0 <= val && val < n)) return ret;

        treap_node_ptr x = val_to_node[val]; x->del = true; 

        if (this->right == x) this->right = (x->l ? x->l : x->p);
        if (x->left) {
            x->left = false;
            if (x->bound) {
                x->bound->R = idx; ret.first = x->bound;
            }
            while (get(x->r) && (!x->l || x->r->val <= x->l->val)) {
                treap_node_ptr y = x->r; x->left_rotate();
                y->left = true;
                bounds.push_back(boundary(y->idx + 1, y->p->idx + 1, idx, n, y->val));
                ret.second.push_back(y->bound = &bounds.back());
            }
            if (x->l) {
                x->l->bound->R = idx;
                bounds.push_back(boundary(x->l->idx + 1, x->p->idx + 1, idx, n, x->l->val));
                ret.second.push_back(x->l->bound = &bounds.back());
            }
            get(x);
        }

        app(idx, val);
        return ret;
    };

    vector<boundary>& get_bounds() {
        return this->bounds;
    }

    ~mex_treap() {
        stack.push_back(this->root);
        while (!stack.empty()) {
            treap_node_ptr x = stack.back(); stack.pop_back();
            if (x->l) stack.push_back(x->l);
            if (x->r) stack.push_back(x->r);
            delete x;
        }
    }
};

int solve(vector<int>& arr) {
    int n = (int) arr.size();
    vector<int> dp(n + 1); dp[0] = 0;

    mex_treap mt(n);
    for (int i = 0; i < n; i++) {
        dp[i + 1] = dp[i];
        for (boundary* b : mt.adv(i, arr[i]).second) dp[i + 1] = max(dp[i + 1], dp[b->l - 1] + b->mex);
    }

    return dp[n];
}

int main() {
    int n; cin >> n;
    vector<int> arr(n); for (int i = 0; i < n; i++) cin >> arr[i];
    cout << solve(arr) << endl;
}

Could use the same technique to solve similar problems, like the sum of the MEX of all subarrays, or the sum of the scores of all partitions. For the former, the solve function would be:

const long long MOD = 1'000'000'007;

long long solve(vector<int>& arr) {
    int n = (int) arr.size();

    mex_treap mt(n);
    for (int i = 0; i < n; i++) mt.adv(i, arr[i]);

    long long ans = 0LL;
    for (boundary b : mt.get_bounds()) ans = (ans + b.mex * (b.l - b.L) % MOD * (b.R - b.r)) % MOD;
    return ans;
}