题解:P12930 [USACO4.3] 逢低吸纳Buy Low, Buy Lower 加强版

· · 题解

一句话题意:求最长下降子序列长度及本质不同的最长下降子序列数目。

首先对序列元素取负数并离散化,这样就变成了最长上升子序列,方便接下来的讨论。

考虑 O(n^2) 的做法,记 f_i 为以 i 结尾的最长上升子序列长度,则

f_i=\max_{1\le j <i, a_j<a_i} f_j+1

再记 g_i 为以 i 结尾的最长上升子序列的方案数。在转移时,若 f_j+1>f_i,直接令 g_i \gets g_j;否则若恰好 f_j+1=f_i,此时累加方案数 g_i \gets g_i+g_j。

但是我们要求本质不同的 LIS 数目,比如说 5 4 3 3 这组数据,5 4 3 和 5 4 3 是算一组的,对于多余的那个 3 要去重。我们只统计在 i 之前最后一次出现的元素的贡献即可。

接下来考虑 LIS 常用优化,显然二分走不通,考虑树状数组。可以在权值树状数组上的每个点维护一个二元组 (f_i,g_i),按照上述规则更新,对于不是最后一次出现的 a_i 减去重复贡献。这样就优化到了 O(n \log n)。

const int N = 1e6 + 5;
const int mod = 1e9 + 7;
constexpr int madd(int a, int b) {return a + b >= mod ? a + b - mod : a + b;} 

long long n, a[N], d[N], last[N];

#define lowbit(x) (x & -x)
struct node {
    int len, cnt;
    node() : len(0), cnt(0) {}
    node(long long l, long long c) : len(l), cnt(c) {}
    node& operator+= (const node& x) {
        if (x.len > len) len = x.len, cnt = x.cnt;
        else if (x.len == len) cnt = madd(cnt, x.cnt);
        return *this;
    }
} tr[N], f[N];
void update(int x, const node& c) {
    for (; x < N; x += lowbit(x)) tr[x] += c;
}
node query(int x) {
    node res;
    for (; x > 0; x -= lowbit(x)) res += tr[x];
    return res;
}

void _main() {
    cin >> n;
    for (int i = 1; i <= n; i++) cin >> a[i], d[i] = -a[i];
    sort(d + 1, d + n + 1);
    int m = unique(d + 1, d + n + 1) - d - 1;
    for (int i = 1; i <= n; i++) a[i] = lower_bound(d + 1, d + m + 1, -a[i]) - d;
    for (int i = 1; i <= n; i++) {
        node q = query(a[i] - 1);
        if (q.len == 0) q.cnt = 1;
        q.len++;
        f[i] = q, update(a[i], q);
        if (last[a[i]] && f[last[a[i]]].len == f[i].len) update(a[i], node{q.len, -f[last[a[i]]].cnt});
        last[a[i]] = i;
    }
    node p = query(m);
    cout << p.len << ' ' << p.cnt;
}