Hangzhou is a beautiful city, especially the West Lake. Recently, the water level of the West Lake got lower and lower because of the hot weather. The experts think that the West Lake is under good situation if the water level is in a certain range. To maintain the good condition of the West Lake, we get at most 2 chances to pour or draw water.
So the question is:
There are N periods, each period the predicted water level of the West Lake is Ai(Ai could be under 0). Now, you can pour water C unit at period X. (if c<0 then it means drawing water.)Then the water level from period X to period N will be increase C(if c<0 then it means the water level will reduce |C|). But you have at most 2 chances.(Do nothing is OK!)
The government wants you to figure out the best plan that could make the periods that the water level is between 1 and N as many as possible.
Input
There are multiple test cases. For each test case:
The first line only contains one integer N(1<=N<=3000),N is the number of periods.
The second line contains N integers, the i-th integer Ai(-N<=Ai<=N) is the height of the water level in i-th period.
Process to the end of input.
Output
One line for each test case. The maximal number of periods that could make the water level in good condition.
Sample Input
6 2 -1 -1 5 -1 2
Sample Output
5
Hint
Pouring 2 unit water at Period 1, then(2,-1,-1,5,-1,2) -> (4,1,1,7,1,4). You get 5 periods (except 4-th) fit the demand.
If you use second chance to draw 1 unit water at Period 4, then(4,1,1,7,1,4) -> (4,1,1,6,0,3). You still get 5 periods (except 5-th) fit the demand.
这道题是一道$dp$ 首先我们先原始搞出$sum[i]$表示不进行任何修改$1 ~ n$满足条件的数的数量
$dp[i](pos)$表示修改的值为$i$时$pos ~ n$满足条件的数的数量 那么假设修改的两次位置为$pos1, pos2$修改的值为$del1, del2$
那么$ans = sum[pos1 - 1] + dp[del1](pos1) + dp[del2][pos2] - dp[del1][pos2]$
相当于把多算的贡献剪掉 然后从后往前做 对于每个$del1$我们需要找的就是$max(dp[del2][pos2] - dp[del1][pos2])$ 这个东西可以在每次搞的时候顺便处理出来
代码
#include <bits/stdc++.h> using namespace std; const int N = 3e3 + 5; int n, dp[3 * N], sum[3 * N], a[3 * N], h[N * 3]; int main( ) { while(scanf("%d", & n) != EOF) { memset(h, 0, sizeof(h)); memset(dp, 0, sizeof(dp)); sum[0] = 0; for(int i = 1;i <= n;i ++) { scanf("%d",& a[i]); sum[i] = sum[i - 1] + (a[i] >= 1 && a[i] <= n); } int ans = 0, ma = 0; for(int i = n;i >= 1;i --) { for(int c = 1 - a[i];c <= n - a[i];c ++) ma = max(ma, ++ dp[c + n]); for(int c = 1 - n;c <= 2 * n;c ++) { ans = max(ans, sum[i - 1] + dp[c + n]); ans = max(ans, sum[i - 1] + dp[c + n] + h[c + n]); } for(int c = 1 - n;c <= 2 * n;c ++) h[c + n] = max(h[c + n], ma - dp[c + n]); } printf("%d\n", ans); } }