思路:
設原數列的LIS = l
因爲0的取值只能使原數列的LIS∈[l,l+1]
故考慮什麼時候0可以使得LIS爲l+1即可
考慮0的前後部分LIS之和爲l且前部分結尾的數<後部分開始的數
於是想到處理出以每個數開始或者結尾的LIS
設b[i],e[i]分別代表以i開始和i結尾的最長LIS
對於每個位置i,j 如果b[i]+e[j] = l & val[i]<val[j] 且i,j之間有0, 則0的取值範圍爲 [val[i]+1, val[j]-1], 然後將0的區間合併
於是想到處理出以j結尾每個長度的v最大al[j]
然後這題注意邊界0的情況, WA1
更新的時候對於[i,j)區間只需要更新pre[i]++, pre[j]--即可
代碼如下
#include<bits/stdc++.h>
using namespace std;
const int MAX_N = 1e5 + 5;
const int INF = 0x3f3f3f3f;
int a[MAX_N], dp[MAX_N];
int b[MAX_N], e[MAX_N];
int LIS, n;
int pre[MAX_N];
int main() {
ios::sync_with_stdio(false);
while (cin >> n) {
fill(pre, pre + 1 + n, 0);
LIS = 0;
for (int i = 0; i < n; i++) cin >> a[i];
fill(dp, dp + n, INF);
for (int i = 0; i < n; i++) {
if (!a[i]) continue;
int l = lower_bound(dp, dp + n, a[i]) - dp;
dp[l] = a[i];
e[i] = l+1;
LIS = max(e[i], LIS);
}
fill(dp, dp + n, -INF);
for (int i = n-1; i >=0; i--) {
if (!a[i]) continue;
int l = lower_bound(dp, dp + n, a[i], greater<int>()) - dp;
dp[l] = a[i];
b[i] = l+1;
}
fill(dp, dp + n+1, -1);
int r = n - 1, l = n - 1;
while (l >= 0) {
if (!a[l]) {
dp[0] = n+1;
for (int i = l + 1; i <= r; i++) {
dp[b[i]] = max(dp[b[i]], a[i]);
}
r = l - 1;
if (dp[LIS] != -1) {
pre[1]++; pre[dp[LIS]]--;
}
}
else {
int end = dp[LIS - e[l]];
if (a[l] < end) {
pre[a[l] + 1]++; pre[end]--;
}
}
l--;
}
long long res = 0;
for (int i = 1; i <= n; i++) {
pre[i] += pre[i - 1];
if (pre[i]) res+=i;
}
cout <<1ll*n*(n+1)/2*LIS+ res << endl;
}
}