题解:P12930 [USACO4.3] 逢低吸纳Buy Low, Buy Lower 加强版
stripe_python · · 题解
一句话题意:求最长下降子序列长度及本质不同的最长下降子序列数目。
首先对序列元素取负数并离散化,这样就变成了最长上升子序列,方便接下来的讨论。
考虑
再记
但是我们要求本质不同的 LIS 数目,比如说 5 4 3 3 这组数据,5 4 3 和 5 4 3 是算一组的,对于多余的那个 3 要去重。我们只统计在
接下来考虑 LIS 常用优化,显然二分走不通,考虑树状数组。可以在权值树状数组上的每个点维护一个二元组
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;
}