I. Longest Increasing Subsequence
Bobo has a sequence a1,a2,…,an. Let f(x) be the length of longest strictly increasing subsequence after replacing all the occurrence of 0 with x.
He would like to find
∑ni=1i∗f(i)
∑
i
=
1
n
i
∗
f
(
i
)
Note that the length of longest strictly increasing subsequence of sequence s1,s2,…,sm is the largest k such that there exists 1≤ i1 < i2 < ··· < ik ≤ m satisfying si1 < si2 < ··· < sik.
Input
The input consists of several test cases and is terminated by end-of-file. The first line of each test case contains an integer n. The second line contains n integers a1,a2,…,an.
Output
For each test case, print an integer which denotes the result.
Constraint • 1≤ n ≤10^5 • 0≤ ai ≤ n •
The sum of n does not exceed 250,000.
Sample Input
2
1 1
3
1 0 3
6
4 0 6 1 0 3
Sample Output
3
14
49
题解
- 这是一个最长递增子序列的应用
- 我们最终需要求出一个和,即:sum = ∑ni=1i∗f(i) ∑ i = 1 n i ∗ f ( i )
- f(x):把输入的序列的所有的0变成 x 之后的最长递增子序列的长度
代码
来自官方的solution
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <iostream>
const int N = 100001;
int a[N], fw[N], bw[N], best[N], delta[N];
void compute(int n, int* a, int* bw)
{
best[0] = 0;
for (int i = 1; i <= n; ++ i) {
best[i] = n;
}
for (int i = 0; i < n; ++ i) {
if (a[i]) {
bw[i] = std::lower_bound(best, best + (n + 1), a[i]) - best;
best[bw[i]] = std::min(best[bw[i]], a[i]);
} else {
bw[i] = 0;
}
}
}
int main()
{
int n;
while (scanf("%d", &n) == 1) {
for (int i = 0; i < n; ++ i) {
scanf("%d", a + i);
}
compute(n, a, bw);
std::reverse(a, a + n);
for (int i = 0; i < n; ++ i) {
if (a[i]) {
a[i] = n + 1 - a[i];
}
}
compute(n, a, fw);
std::reverse(a, a + n);
for (int i = 0; i < n; ++ i) {
if (a[i]) {
a[i] = n + 1 - a[i];
}
}
std::reverse(fw, fw + n);
int global = *std::max_element(bw, bw + n);
a[n] = n + 1, fw[n] = 0;
for (int i = 0; i <= n; ++ i) {
best[i] = n;
}
memset(delta, 0, sizeof(*delta) * (n + 1));
for (int i = 0; i <= n; ++ i) {
if (a[i]) {
if (best[global - fw[i]] + 1 <= a[i] - 1) {
delta[best[global - fw[i]] + 1] ++;
delta[a[i]] --;
}
} else {
int j = i - 1;
for (; j >= 0 && a[j]; -- j) {
best[bw[j]] = std::min(best[bw[j]], a[j]);
}
if (j == -1) {
best[0] = std::min(best[0], 0);
}
}
}
int sum = 0;
long long result = 0;
for (int i = 1; i <= n; ++ i) {
sum += delta[i];
result += 1LL * i * (sum ? global + 1 : global);
}
std::cout << result << "\n";
}
}