这道 模版题也能用区间 做
但复杂度高,只有 分
① 确定状态
: 表示区间 的最大子段和
② 确定答案
③ 确定状态转移方程
区间 可以向左或向右增加数字
只需比较向左加入和向右加入的结果即可
④ 确定初始值和边界条件
40分代码
#include<bits/stdc++.h>
using namespace std;
const int N=2e3+7;
int n;
int a[N],dp[N][N];
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin>>n;
int maxn=INT_MIN;
for(int i=1;i<=n;i++){
cin>>a[i];
dp[i][i]=a[i];
maxn=max(maxn,a[i]);//区间长度为1的单独计算
}
for(int len=2;len<=n;len++){
for(int l=1;l+len-1<=n;l++){
int r=l+len-1;
dp[l][r]=max(dp[l+1][r]+a[l],dp[l][r-1]+a[r]);
maxn=max(maxn,dp[l][r]);
}
}
cout<<maxn;
return 0;
} 本题两种贡献分别是 和 ,序列又不会变,所以上面那两种合并的方式其实得到的和是一模一样的
2.P2858 [USACO06FEB] Treats for the Cows G/S
首先考虑贪心,可以写出 分代码
#include<bits/stdc++.h>
using namespace std;
const int N=1e3+7;
int n;
int a[N],dp[N][N];
int ans=0;
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin>>n;
for(int i=1;i<=n;i++){
cin>>a[i];
}
int front=1,last=n;
int day=1;
while(front<=last){
if(a[front]<a[last]){
ans+=a[front]*day;
front++;
}
else{
ans+=a[last]*day;
last--;
}
day++;
}
cout<<ans;
return 0;
} 拿不到全分一定是因为有 数据
例如12 12 12 12 1 13
所以考虑用区间
由图可知,从下往上每次在左边增加一个或在右边增加一个
类似于上一题,但每次增加
① 确定状态
: 表示区间 卖零食的最大收益
② 确定答案
③ 确定状态转移方程
④ 确定初始值和边界条件
Ac Code
#include<bits/stdc++.h>
using namespace std;
const int N=2e3+7;
const int INF=1e9;
int n;
int a[N],dp[N][N];
int ans=0;
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin>>n;
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
dp[i][j]=-INF;
}
}
for(int i=1;i<=n;i++){
cin>>a[i];
dp[i][i]=a[i]*n;
}
for(int len=2;len<=n;len++){
for(int l=1;l+len-1<=n;l++){
int r=l+len-1;
//天数是n-len+1
dp[l][r]=max(dp[l+1][r]+a[l]*(n-len+1),dp[l][r-1]+a[r]*(n-len+1));
}
}
cout<<dp[1][n];
return 0;
} ① 确定状态
: 表示区间 内的数字已经安排好了,并且最后一个放入 的方案数量
: 表示区间 内的数字已经安排好了,并且最后一个放入 的方案数量
② 确定答案
③ 确定状态转移方程
④ 确定初始值和边界条件
边界条件 :
初始值 :
Ac Code
#include<bits/stdc++.h>
using namespace std;
const int N=1e3+7;
const int INF=1e9;
const int mod=19650827;
int n;
int a[N],dp[N][N][2];
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin>>n;
for(int i=1;i<=n;i++){
cin>>a[i];
dp[i][i][0]=1;
dp[i][i][1]=0;
}
for(int len=2;len<=n;len++){
for(int l=1;l+len-1<=n;l++){
int r=l+len-1;
//上一个是a[l+1]新来的是a[l]
if(a[l]<a[l+1]){
dp[l][r][0]+=dp[l+1][r][0];
dp[l][r][0]%=mod;//记得取模
}
//上一个是a[r]新来的是a[l]
if(a[l]<a[r]){
dp[l][r][0]+=dp[l+1][r][1];
dp[l][r][0]%=mod;
}
//上一个是a[l]新来的是a[r]
if(a[l]<a[r]){
dp[l][r][1]+=dp[l][r-1][0];
dp[l][r][1]%=mod;
}
//上一个是a[r-1]新来的是a[r]
if(a[r-1]<a[r]){
dp[l][r][1]+=dp[l][r-1][1];
dp[l][r][1]%=mod;
}
}
}
cout<<(dp[1][n][0]+dp[1][n][1])%mod;
return 0;
} 

