Attention:
①前缀和
②差分
B[i]是当p是i时,非零段数量与B[i - 1]相比的变化量。因此当A[i] > A[i - 1]时,就是在说,因着新加入的A[i],使得p = A[i - 1]时的非零段数量+1,使得p = A[i]时的非零数段 - 1。
而从B[0]到B[i]的各项之和,即为p = i时的非零段数量。
以下是自己第一次完成的暴力70分代码:
#include<bits/stdc++.h>
using namespace std;
const int maxn = 500010;
int A[maxn] = { 0 };
int B[maxn] = { 0 };
int main()
{
ios::sync_with_stdio(false);
int n;
cin >> n;
for(int i = 1; i <= n; ++i)
cin >> A[i];
// 计算原数组的非0段,判断是否无需改动
int org = 0, flag = 0, no_op = 1, max = 0;
for(int i = 1; i <= n + 1; ++i){
if(A[i] > max) max = A[i];
if(A[i] > 0){
if(A[i - 1] != 0 || A[i + 1] != 0) no_op = 0;
}
if(A[i] > 0 && flag == 0)flag = 1;
else if(A[i] == 0 && flag == 1){
org++; flag = 0;
}
}
if(no_op == 1){
cout << org; return 0;
}
if(max == 0){
cout << "0"; return 0;
}
int max_nozero = org;
for(int i = 2; i <= max; ++i){
int flag = 0, org_b = 0;
for(int j = 1; j <= n; ++j){
if(A[j] < i)B[j] = 0;
else B[j] = A[j];
}
for(int j = 1; j <= n + 1; ++j){
if(B[j] > 0 && flag == 0) flag = 1;
else if(B[j] == 0 && flag == 1){
flag = 0; org_b++;
}
}
if(org_b > max_nozero) max_nozero = org_b;
}
cout << max_nozero;
return 0;
}
以下是参考后得到的采用前缀和+差分的算法
#include<bits/stdc++.h>
using namespace std;
const int maxn = 500010;
int A[maxn] = { 0 };
int B[maxn] = { 0 };
int main()
{
ios::sync_with_stdio(false);
int n;
cin >> n;
for(int i = 1; i <= n; ++i){
cin >> A[i];
if(A[i] > A[i - 1])
{
B[A[i - 1]]++; B[A[i]]--;
}
}
int ans = 0, t = 0;
for(int i = 0; i <= maxn; ++i){
t += B[i]; ans = max(t, ans);
}
cout << ans;
return 0;
}