Codeforces Round #267 (Div. 2) C. George and Job 题解(01背包)

题目链接

题目大意

给你一个长度为n的数组(n<=5000)的,要你找出k个m个字串(不相交)使得这个总和最大,求其最大值

题目思路

看到数据范围就明白显然是一个dp,但是自己不知道写的是啥写了一个 O ( n 3 ) O(n^3) 的T了,一直是又wa又T。
其实这种题目很简单,就是一种模板题,你要求什么就定义什么,这样你就可以定义dp[i][j]为[1,i]中选了j的子串的最大值,然后前缀和处理一下就行了,好久没写01背包的普通版本了,一定要注意 **dp[i][j]=dp[i-1][j]**这个语句别忘了

代码

#include<set>
#include<map>
#include<queue>
#include<stack>
#include<cmath>
#include<cstdio>
#include<vector>
#include<string>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<unordered_map>
#define fi first
#define se second
#define debug printf(" I am here\n");
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> pii;
const ll INF=0x3f3f3f3f3f3f3f3f;
const int maxn=5e3+5,inf=0x3f3f3f3f,mod=998244353;
const double eps=1e-10;
int n,m,k,a[maxn];
ll pre[maxn],dp[maxn][maxn],v[maxn];
signed main(){
    scanf("%d%d%d",&n,&m,&k);
    for(int i=1;i<=n;i++){
        scanf("%d",&a[i]);
        pre[i]=pre[i-1]+a[i];
        if(i>=m){
            v[i]=pre[i]-pre[i-m];
        }
    }
    for(int i=1;i<=n;i++){
        for(int j=1;j<=k;j++){
            dp[i][j]=dp[i-1][j];
            //这个语句不要忘!!!!
            if(i>=m){
                if(j>1&&dp[i-m][j-1]==0) continue;
                dp[i][j]=max(dp[i][j],dp[i-m][j-1]+v[i]);
            }
        }
    }
    printf("%lld\n",dp[n][k]);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/m0_46209312/article/details/107957928