---
id: 1193
lang: en
translation_of: index.md
source_sha256: 5cdd38ff8b92664e08342f5d69ac24cf62ba3c09f9cbdb98ddc693d43c306db0
title: "BZOJ4361: isn — Solution"
description: "Count the non-decreasing subsequences of each length with a DP sped up by a Fenwick tree, then get each contribution by inclusion–exclusion."
tags: ["OI","DP","Fenwick Tree","Combinatorics"]
translated: 2026-11-27
translator: Claude Opus 5.5
translator_model: claude-opus-5-5
translation_notes:
  - "搞一个 DP (a casual “rig up a DP”) rendered as “whip up a DP”; treated as casual wording rather than slang, so no chip."
---

## Solution

This problem is really interesting. First, whip up a $DP$ to count the non-decreasing subsequences of each length; the equation is:

$$
f[i, j] = \sum_{k < i, a_k \leq a_i} f[k, j - 1]
$$

We notice that it can be optimized with a Fenwick tree, so the complexity here is $O(n^2 \log n)$. Let $g[i] = \sum_{i = 1} f[i, n]$, and consider the contribution to the answer. For a given $i$, there are $g[i] * (n - i)!$ ways to carry out the transformation, but note that these $(n - i)!$ include the cases where the transformation was already finished early, that is, the cases where we deleted valid elements from a valid sequence, and that definitely won't do. Consider inclusion–exclusion: the contribution is $g[i] (n-i)! - g[i+1] (n - i - 1)!(i + 1)$, which represents the ways of choosing $i+1$ valid elements among these.

<!--more-->

## Code

```cpp
// BZ4361.cpp
#include <bits/stdc++.h>
#define ll long long
using namespace std;
const ll MAX_N = 2010, mod = 1e9 + 7;
ll f[MAX_N][MAX_N], g[MAX_N], arr[MAX_N], n, tree[MAX_N][MAX_N], level[MAX_N];
vector<ll> vec;

ll lowbit(ll x) { return x & (-x); }

ll query(ll id, ll x)
{
    ll ans = 0;
    while (x)
        ans = (ans + tree[id][x]) % mod, x -= lowbit(x);
    return ans;
}

void add(ll id, ll x, ll d)
{
    while (x <= n)
        tree[id][x] = (tree[id][x] + d) % mod, x += lowbit(x);
}

int main()
{
    scanf("%lld", &n);
    for (ll i = 1; i <= n; i++)
        scanf("%lld", &arr[i]), vec.push_back(arr[i]);
    level[0] = 1;
    for (ll i = 1; i < MAX_N; i++)
        level[i] = level[i - 1] * i % mod;

    sort(vec.begin(), vec.end()), vec.erase(unique(vec.begin(), vec.end()), vec.end());
    for (ll i = 1; i <= n; i++)
        arr[i] = lower_bound(vec.begin(), vec.end(), arr[i]) - vec.begin() + 1;

    add(0, 1, 1);
    for (ll i = 1; i <= n; i++)
        for (ll j = i; j >= 1; j--)
        {
            f[i][j] = (f[i][j] + query(j - 1, arr[i])) % mod;
            add(j, arr[i], f[i][j]);
        }
    for (ll i = 1; i <= n; i++)
        for (ll j = i; j <= n; j++)
            g[i] = (g[i] + f[j][i]) % mod;
    ll ans = 0;
    for (ll i = 1; i <= n; i++)
        ans = (ans + g[i] * level[n - i] % mod - g[i + 1] * level[n - i - 1] % mod * (i + 1) % mod + mod) % mod;
    printf("%lld", ans);
    return 0;
}
```
