青鸟 题解

· · 个人记录

Generated by GPT-6 Astra high.

1. Reverse the operations: remove positions

Fix a proposed final array b. Let V be the set of positions not yet removed.

For j\in V, let L,R be its nearest remaining neighbors, using sentinel positions 0,n+1.

We may remove j when

L<b_j<R.

Why? After constructing the final values at the other remaining positions, we can paint

[\min(j,b_j),\max(j,b_j)]

with color b_j. This affects j, but no other remaining position.

Thus removal means:

“We can restore this position later without disturbing the positions still under consideration.”

A final array is reachable precisely when some sequence of these removals leaves only positions satisfying

b_i=a_i.

The reverse direction follows from the painting construction. For necessity, consider the last painting operation touching the remaining positions: one of the positions nearest to its color-index is removable.

2. Remove everything possible: obtain a unique core

Removing positions only expands the intervals between surviving neighbors. Therefore:

Once a position becomes removable, removing other positions cannot make it unremovable.

Consequently, repeatedly removing any available position produces the same final set, regardless of order. Call it the core.

Then

\boxed{ b\text{ is reachable} \iff b_i=a_i\text{ at every core position }i. }

This gives a duplicate-free way to classify final arrays: by their unique core.

Suppose the core positions are

c_1<c_2<\cdots<c_k,

with sentinels

c_0=0,\qquad c_{k+1}=n+1.

There are two requirements.

Requirement A: gaps disappear completely

Every open interval

(c_j,c_{j+1})

must be fully removable while its two endpoints remain.

Requirement B: core positions cannot disappear

At core position c_j, its value is a_{c_j}, and it must satisfy

\boxed{ a_{c_j}\le c_{j-1} \quad\text{or}\quad a_{c_j}\ge c_{j+1}. }

Otherwise it would be removable.

We will calculate gap weights first, then sum over cores.

3. Gap weights depend only on length

Let F(l,r) be the sum of weights of all assignments in the open interval (l,r) that are fully removable, keeping l,r fixed.

The empty interval has weight

F(l,l+1)=1.

Write

f_m=F(0,m+1).

A fully removable gap of length m=r-l-1 uses only values strictly between l and r.

Subtract l from every index and every value. This preserves removability and decreases the sum of the values by lm.

Therefore,

\boxed{ F(l,r)=p^{l(r-l-1)}f_{r-l-1}. }

This identity is what makes the full algorithm quadratic.

We only need to compute f_0,\ldots,f_n, not a quadratic table of unrelated interval states.

4. Deriving the gap DP

This is the hardest part: different removal orders must not be counted separately.

Define

q_x=p^x, \qquad Q(t)=\sum_{x=0}^{t-1}q_x.

The total weight of choosing a value strictly between u,v is

W(u,v)=Q(v)-Q(u+1).

All arithmetic below is modulo

M=10^9+7.

4.1 Inclusion–exclusion over the last remaining position

Consider the gap (l,r).

Let E_j mean that position j can be the last position removed.

If j is last:

Hence

\operatorname{wt}(E_j)=F(l,j)W(l,r)F(j,r).

We cannot simply sum these: an array may permit several choices of last position.

For a nonempty set

S=\{s_1<\cdots<s_k\}, \quad s_0=l,\quad s_{k+1}=r,

the intersection has weight

\boxed{ \operatorname{wt}\left(\bigcap_{j\in S}E_j\right) = \prod_{h=0}^{k}F(s_h,s_{h+1}) \prod_{h=1}^{k}W(s_{h-1},s_{h+1}). }

Here:

One way to justify sufficiency is the following useful characterization:

An assignment inside (l,r) is fully removable iff all its values lie in (l,r) and there is no pair i<j with

b_i\ge j,\qquad b_j\le i.

Such a pair blocks itself forever. Conversely, a nonempty stuck core must contain such a pair: its first position points right, its last points left, so some consecutive pair forms a right-to-left transition.

The restrictions in the intersection formula prevent these blocking pairs across its gaps.

Now inclusion–exclusion gives

F(l,r)= \sum_{\varnothing\ne S\subseteq(l,r)} (-1)^{|S|+1} \prod_{h=0}^{|S|}F(s_h,s_{h+1}) \prod_{h=1}^{|S|}W(s_{h-1},s_{h+1}).

This looks exponential, but the factor

W(u,v)=Q(v)-Q(u+1)

can be separated into two terms.

4.2 Compress the inclusion–exclusion sum

We only need the case l=0.

Think of a selected set as an increasing path starting at 0. Let T(i,j) aggregate signed partial paths whose last two positions are i,j.

Initialize the paths with no selected internal position:

T(0,j)=F(0,j).

Extending a path from i,j to k contributes

-T(i,j)\,W(i,k)\,F(j,k).

Define two aggregates:

A_j=\sum_{i<j}T(i,j), \qquad B_j=\sum_{i<j}Q(i+1)T(i,j).

Then extension to k becomes

-F(j,k)\bigl(Q(k)A_j-B_j\bigr).

Inclusion–exclusion implies a cancellation:

A_1=1,\qquad A_j=0\quad(j>1).

Indeed, for j>1, the initial contribution F(0,j) cancels all nonempty signed paths ending at j.

Thus only the B_j array is needed.

Final recurrence

Initialize

f_0=1,\qquad B_1=Q(1)=1.

For r=2,3,\ldots,n+1, define

C_j(r)= \begin{cases} Q(r)-Q(1),&j=1,\\ -B_j,&j>1. \end{cases}

For each 1\le j<r, let

D_j= f_{r-j-1}\, p^{j(r-j-1)}\, C_j(r).

Then

\boxed{ f_{r-1}=\sum_{j=1}^{r-1}D_j }

and

\boxed{ B_r= Q(1)f_{r-1} - \sum_{j=1}^{r-1}Q(j+1)D_j. }

There are O(n^2) terms.

Avoid exponentiation inside the loops

For fixed j, when r increases by one,

p^{j(r-j-1)}

is multiplied by p^j=q_j.

Maintain these powers incrementally in an array. No modular exponentiation is needed inside the DP.

As a sanity check, for p=1:

f_0,f_1,f_2,f_3,f_4 = 1,1,3,14,86.

5. Count the cores in another O(n^2) DP

Assume the gap weights are available through

F(j,k)=f_{k-j-1}p^{j(k-j-1)}.

Conceptually, define dp[i][j] for partial cores whose last two positions are i,j.

When we choose the next core position k>j, position j is valid exactly when

a_j\le i \quad\text{or}\quad a_j\ge k.

So the coefficient needed for the transition is

\sum_{i<j} dp[i][j]\,[a_j\le i\text{ or }a_j\ge k].

This only needs two aggregates:

T_j=\sum_{i<j}dp[i][j], U_j=\sum_{\substack{i<j\\i\ge a_j}}dp[i][j].

Therefore the transition coefficient is

\boxed{ S(j,k)= \begin{cases} T_j,&k\le a_j,\\ U_j,&k>a_j. \end{cases} }

This avoids storing the two-dimensional DP.

Initialization

If k is the first core position, the prefix gap is (0,k):

dp[0][k]=f_{k-1}q_{a_k}.

Add this to T_k.

It belongs to U_k exactly when

0\ge a_k,

which means a_k=0.

The empty-core contribution is simply

f_n.

Transition

For 1\le j<k\le n, compute

v=S(j,k)\,F(j,k)\,q_{a_k}.

Update

T_k\gets T_k+v.

If j\ge a_k, also update

U_k\gets U_k+v.

To finish at the right sentinel k=n+1, add

S(j,n+1)F(j,n+1)

to the answer. There is no sentinel value weight.

Again, this takes O(n^2) time and O(n) space.

6. Complete C++17 code

The code below uses standard input/output. For the original file-based contest, enable the two freopen lines.

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

using int64 = long long;

constexpr int64 MOD = 1000000007;

int64 solve(int n, int64 p, const vector<int>& a) {
    // q[x] = p^x
    vector<int64> q(n + 3, 1);
    for (int i = 1; i <= n + 2; ++i) {
        q[i] = q[i - 1] * p % MOD;
    }

    // Q[t] = q[0] + ... + q[t - 1]
    vector<int64> Q(n + 3, 0);
    for (int i = 0; i <= n + 1; ++i) {
        Q[i + 1] = (Q[i] + q[i]) % MOD;
    }

    // Phase 1: fully removable gap weights.
    vector<int64> f(n + 1, 0);
    vector<int64> B(n + 2, 0);
    vector<int64> power(n + 2, 0);

    f[0] = 1;
    B[1] = Q[1];

    for (int r = 2; r <= n + 1; ++r) {
        // New j = r - 1 has gap length zero.
        power[r - 1] = 1;

        int64 sum = 0;
        int64 moment = 0;

        for (int j = 1; j < r; ++j) {
            int64 coefficient;

            if (j == 1) {
                coefficient = (Q[r] - Q[1] + MOD) % MOD;
            } else {
                coefficient = (MOD - B[j]) % MOD;
            }

            // power[j] = p^(j * (r - j - 1))
            int64 term = f[r - j - 1] * power[j] % MOD;
            term = term * coefficient % MOD;

            sum = (sum + term) % MOD;
            moment = (moment + Q[j + 1] * term) % MOD;

            // Prepare for the next r.
            power[j] = power[j] * q[j] % MOD;
        }

        f[r - 1] = sum;
        B[r] = (Q[1] * sum % MOD - moment + MOD) % MOD;
    }

    // Phase 2: count unique cores.
    vector<int64> total(n + 2, 0);
    vector<int64> eligible(n + 2, 0);

    for (int k = 1; k <= n; ++k) {
        int64 value = f[k - 1] * q[a[k]] % MOD;

        total[k] = value;

        // Previous core position is sentinel 0.
        if (a[k] == 0) {
            eligible[k] = value;
        }
    }

    // Empty core: every position is removable.
    int64 answer = f[n];

    for (int j = 1; j <= n; ++j) {
        // At k = j + 1, p^(j * (k - j - 1)) = 1.
        int64 shift = 1;

        for (int k = j + 1; k <= n + 1; ++k) {
            int64 coefficient =
                (k <= a[j] ? total[j] : eligible[j]);

            int64 value = coefficient * f[k - j - 1] % MOD;
            value = value * shift % MOD;

            if (k == n + 1) {
                // Right sentinel has no value weight.
                answer = (answer + value) % MOD;
            } else {
                value = value * q[a[k]] % MOD;

                total[k] = (total[k] + value) % MOD;

                if (j >= a[k]) {
                    eligible[k] = (eligible[k] + value) % MOD;
                }
            }

            shift = shift * q[j] % MOD;
        }
    }

    return answer;
}

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

    // freopen("bird.in", "r", stdin);
    // freopen("bird.out", "w", stdout);

    int c, t;
    cin >> c >> t;

    while (t--) {
        int n;
        int64 p;
        cin >> n >> p;

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

        cout << solve(n, p, a) << '\n';
    }

    return 0;
}

Complexity

For each test case:

\boxed{\text{Time }O(n^2),\qquad \text{Space }O(n).}

No modular division or inverse is used, so p=1 needs no special handling.

The solution in four steps

  1. Reverse painting into position removal.
  2. Use the unique unremovable core to avoid counting operation orders.
  3. Compute fully removable gap weights with inclusion–exclusion, then use index-shift symmetry to reduce them to a one-dimensional array.
  4. Count cores with two aggregate states per last position.

The major obstacle was not the final core DP. It was finding a duplicate-free gap recurrence—and then noticing that

\boxed{F(l,r)=p^{l(r-l-1)}f_{r-l-1}}

turns the cubic interval computation into the full quadratic solution.