https://codeforces.com/contest/958/problem/C2
这道题是明显的区间dp,我们跑三重for循环,模拟S的长度从1-n,分成的区间数(1-k),用二维数组dp[n][k]表示
状态转移方程 f[i][j]=max(f[k][j−1]+(sum[i]−sum[k]+p)modp)(1≤i≤N,1≤j≤K,0≤k<i),其中sum是取模之后的前缀和运算结果
然而,因为n太大了,超时。。。
Time Limit Exceeded on test 24
虽然超时,但至少说明思路没问题,超时代码:
#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<vector>
#include<set>
#include<map>
#include<queue>
#include<cmath>
#define ll long long
#define mod 1000000007
#define inf 0x3f3f3f3f
using namespace std;
#define ll long long
using namespace std;
ll dp[20005][55];
ll sum[20005];
int main()
{
int n, k, p;
int tmp;
cin>>n>>k>>p;
//memset(dp, 0, sizeof(0));
sum[0] = 0;
for(int i = 1; i <= n; i ++)
{
cin>>tmp;
tmp %= p;
sum[i] = (sum[i-1] + tmp) % p;
}
memset(dp, -0x3f, sizeof(dp));
dp[0][0] = 0;
for(int i = 1; i <= n; i ++)
{
for(int j = 1; j <= k; j ++)
{
for(int o = 0; o <= i; o ++)
{
dp[i][j] = max(dp[i][j], dp[o][j-1] + ((sum[i] - sum[o] + p) % p));
}
}
}
cout<<dp[n][k]<<endl;
return 0;
}
然后去看题解,十个人里面有九个是遍历的p,大家的思路不约而同,感觉大佬是真的把这道题当水题做了,因为p太小了,所以我们考虑枚举%p之后的结果
状态转移方程变成这样的:dp[i][j] = max(dp[i][j], dp[k][j-1] + (i-k+p)%p)
时间复杂度大大降低。。。
ac代码
#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<vector>
#include<set>
#include<map>
#include<queue>
#include<cmath>
#define ll long long
#define mod 1000000007
#define inf 0x3f3f3f3f
using namespace std;
#define ll long long
using namespace std;
ll dp[20005][55];
ll sum[20005];
int main()
{
int n, k, p;
int tmp;
cin>>n>>k>>p;
sum[0] = 0;
for(int i = 1; i <= n; i ++)
{
cin>>tmp;
//tmp %= p;
sum[i] = (sum[i-1] + tmp) % p;
}
memset(dp, -0x3f, sizeof(dp));
dp[0][0] = 0;
for(int i = 1; i <= n; i ++)
{
for(int j = 1; j <= k; j ++)
{
for(int o = 0; o < p; o ++)
{
dp[sum[i]][j] = max(dp[sum[i]][j], dp[o][j-1] + ((sum[i] - o + p) % p));
}
}
}
cout<<dp[sum[n]][k]<<endl;
return 0;
}