练习三1003

来源:互联网 发布:微信支付php 完整源码 编辑:程序博客网 时间:2024/06/15 16:28
Nowadays, a kind of chess game called “Super Jumping! Jumping! Jumping!” is very popular in HDU. Maybe you are a good boy, and know little about this game, so I introduce it to you now.<br><br><center><img src=/data/images/1087-1.jpg></center><br><br>The game can be played by two or more than two players. It consists of a chessboard(棋盘)and some chessmen(棋子), and all chessmen are marked by a positive integer or “start” or “end”. The player starts from start-point and must jumps into end-point finally. In the course of jumping, the player will visit the chessmen in the path, but everyone must jumps from one chessman to another absolutely bigger (you can assume start-point is a minimum and end-point is a maximum.). And all players cannot go backwards. One jumping can go from a chessman to next, also can go across many chessmen, and even you can straightly get to end-point from start-point. Of course you get zero point in this situation. A player is a winner if and only if he can get a bigger score according to his jumping solution. Note that your score comes from the sum of value on the chessmen in you jumping path.<br>Your task is to output the maximum value according to the given chessmen list.<br>
 

Input
Input contains multiple test cases. Each test case is described in a line as follow:<br>N value_1 value_2 …value_N <br>It is guarantied that N is not more than 1000 and all value_i are in the range of 32-int.<br>A test case starting with 0 terminates the input and this test case is not to be processed.<br>
 

Output
For each case, print the maximum according to rules, and one line one case.<br>
题意:就是让你求最长上升子序列的和
思路:就是个DP搜索而已,用dp也能做,只是耗费时间,这里用动态规划的思想,用空间换时间,实现记忆化搜索,利用方程dp[i]=max{dp[j]+a[i]}的思想。

代码:

#include<iostream>#include<string.h>#include<algorithm>#include<cmath>using namespace std;int main(){    int n,temp,maxn;    int a[1001];//记录数据    int sum[1001];//记录每个位置最长升序子序列的和    memset(a,0,sizeof(a));    memset(sum,0,sizeof(sum));    while(cin>>n&&n!=0)    {        for(int i=1;i<=n;i++)        {            cin>>a[i];        }        maxn=-1;//实现记忆化搜索寻找最大的sum[i]        for(int i=1;i<=n;i++)//两个for实现了遍历        {            temp=0;            for(int j=i-1;j>=1;j--)            {                if(a[j]<a[i]&&temp<sum[j])  temp=sum[j];            }                sum[i]=a[i]+temp;                maxn=max(maxn,sum[i]);//寻找最大sum[i]        }        cout<<maxn<<endl;    }    return 0;}
。。
感想:老师上课讲的题,这里要联想到M段子段的情况,子矩阵之和,以及二维的DP问题(滑雪问题)。。

0 0