定义:
sum[i]=a[1]+a[2]+...+a[i] 即,sum[i]为序列a的前缀和
dp[i] = sum[i] - min(sum[j]) (i-j<m) 即,dp[i]为以i结尾的满足长度不大于m的最大连续和
则:
答案为 max(dp[i]) (1≤i≤n)
#include <cstdio> #include <iostream> using namespace std; int sum[300005]; int st[300005]; int main () { int n, m, x, l, r, minn, ans; while(scanf("%d%d", &n, &m) != EOF) { for(int i=1; i<=n; i++) { scanf("%d", &x); sum[i] = sum[i-1] + x; } // 维护一个单调递增队列 l=r=0; st[r++]=0; ans = sum[1]; for(int i=1; i<=n; i++) { while(l<r && i-st[l] > m) l++; minn = sum[st[l]]; if(ans < sum[i]-minn) ans = sum[i] - minn; while(l<r && sum[i] < sum[st[r-1]]) r--; st[r++] = i; } printf("%d\n", ans); } return 0; }
时间: 2024-12-10 03:57:24