之前做過最長遞增子序列,這次碰到一個最大遞增子序列,題意如下:
有一個跳跳棋棋盤,棋盤上面每個位置都有一個正數,你只能從左到右跳,每踩到一個位置,你的總分就加上該位置的數,一次可以跳一個或者多個,並且,你踩的數只能越踩越大
求最大你能得到的總分
狀態轉移公式如下:
dp[i] = max{ dp[0],dp[1],....dp[j] } &&chess[max_pos]<chess[i] (1<=j<i)
(其中,chess[]數組保存了棋盤上的數,dp[max_pos]是前j個位置中,最大的那個)
代碼如下:
#include<cstdio>
const int N = 1010;
void Max(__int64 dp[],int chess[],int len){
__int64 max=dp[len];
int pos=len;
for(int i=len-1;i>=1;i--){
if(chess[pos]>chess[i]&&max<dp[i]){
max = dp[i];
}
}
dp[len] = max + chess[len];//更新dp數組
}
int main(){
int n,chess[N]={0};
__int64 dp[N];
while(scanf("%d",&n)&&n){
for(int i=0;i<N;i++)dp[i]=0;
for(int i=1;i<=n;i++)scanf("%d",&chess[i]);
for(int i=1;i<=n;i++){
Max(dp,chess,i);//找出符合chess[max_pos]<chess[i]的dp[max_pos]
}
int tmp = 0;
for(int i=1;i<=n;i++){
if(dp[i]>tmp){
tmp = dp[i];
}
}
printf("%d\n",tmp);
}
}