Problem - 1796D - Codeforces
思路:想了个假dp做法推了半天,果然是dp。考虑用dp[i][j]表示以i结尾的,并且选择j个+x的最长连续子序列,那么如果我不选择第i位,那么会有f[i][j]=max(w[i]-x,f[i-1][j]+w[i]-x),同时i>j也要满足,因为如果i<=j,那么所有的我必须都要选择,如果第i位我选择,那么会有
f[i][j]=max(w[i]+x,f[i-1][j-1]+w[i]+x),同时要满足j-1>=0另外我们还要保证我们总共要选择k个,在前i个中我们选择了j个,那么要满足在n-i中至少选择k-j个,即要满足n-i>=k-j,所以j>=k-n+i,所以我们只要算所有的f[i][j]同时取一个max即可,因为我们保证了我们枚举到的i,j都满足总共要选择k个的条件
// Problem: D. Maximum Subarray
// Contest: Codeforces - Educational Codeforces Round 144 (Rated for Div. 2)
// URL: https://codeforces.com/problemset/problem/1796/D
// Memory Limit: 512 MB
// Time Limit: 2000 ms
#include<iostream>
#include<cstring>
#include<string>
#include<sstream>
#include<bitset>
#include<deque>
#include<cmath>
#include<cstdio>
#include<algorithm>
#include<queue>
#include<map>
#include<stack>
#include<vector>
#include<set>
#include<cstdlib>
#define fi first
#define se second
#define i128 __int128
using namespace std;
typedef long long ll;
typedef double db;
typedef pair<int,int> PII;
typedef pair<int,pair<int,int> > PIII;
const double eps=1e-7;
const int N=5e5+7 ,M=5e5+7, INF=0x3f3f3f3f,mod=1e9+7,mod1=998244353;
const long long int llINF=0x3f3f3f3f3f3f3f3f;
inline ll read() {ll x=0,f=1;char c=getchar();while(c<'0'||c>'9') {if(c=='-') f=-1;c=getchar();}
while(c>='0'&&c<='9') {x=(ll)x*10+c-'0';c=getchar();} return x*f;}
inline void write(ll x) {if(x < 0) {putchar('-'); x = -x;}if(x >= 10) write(x / 10);putchar(x % 10 + '0');}
inline void write(ll x,char ch) {write(x);putchar(ch);}
void stin() {freopen("in_put.txt","r",stdin);freopen("my_out_put.txt","w",stdout);}
bool cmp0(int a,int b) {return a>b;}
template<typename T> T gcd(T a,T b) {return b==0?a:gcd(b,a%b);}
template<typename T> T lcm(T a,T b) {return a*b/gcd(a,b);}
void hack() {printf("\n----------------------------------\n");}
int T,hackT;
int n,m,k;
int w[N];
ll f[N][21];
void solve() {
n=read(),k=read();
int x=read();
for(int i=1;i<=n;i++) w[i]=read();
for(int i=1;i<=n;i++) {
for(int j=0;j<=k;j++) {
f[i][j]=-llINF;
}
}
ll res=0;
for(int i=1;i<=n;i++) {
for(int j=max(0,k+i-n);j<=min(i,k);j++) {
if(j<i) f[i][j]=max((ll)w[i]-x,f[i-1][j]+w[i]-x);
if(j>0) f[i][j]=max(f[i][j],max((ll)w[i]+x,f[i-1][j-1]+w[i]+x));
f[i][j]=max(f[i][j],0ll);
res=max(res,f[i][j]);
}
}
printf("%lld\n",res);
}
int main() {
// init();
// stin();
scanf("%d",&T);
// T=1;
while(T--) hackT++,solve();
return 0;
}
参考博客:https://www.cnblogs.com/onlyblues/p/17177714.html
这个博客讲的挺详细的