前缀后缀和搞一搞,然后枚举一下区间,找出最大值
1 #include <iostream> 2 #include <algorithm> 3 using namespace std; 4 5 const int maxn = 1e5 + 5; 6 int a[maxn], f[maxn], b[maxn], c[maxn]; 7 8 int main() 9 { 10 ios::sync_with_stdio(false); 11 int n, k; 12 cin >> n >> k; 13 for (int i = 1; i <= n; i++) 14 cin >> a[i]; 15 for (int i = 1; i <= n; i++) 16 cin >> f[i]; 17 //前缀和 18 for (int i = 1; i <= n; i++) 19 if (f[i])b[i] = b[i - 1] + a[i]; 20 else b[i] = b[i - 1]; 21 //后缀和 22 for (int i = n; i>0; i--) 23 if (f[i])c[i] = c[i + 1] + a[i]; 24 else c[i] = c[i + 1]; 25 26 long long s = 0; 27 for (int i = 1; i <= k; i++)s += a[i]; 28 long long ans = 0; 29 for (int i = k; i <= n; i++){ 30 ans = max(b[i - k] + s + c[i + 1], ans); 31 s = s - a[i - k + 1] + a[i + 1]; 32 } 33 cout << ans; 34 return 0; 35 }