1.简单题意
这道题要求的是最长上升子序列的和。
2.解题思路
用一个sum数组存储子问题的解。(sum对应的下标 i 表示,从0到i,最长上升子序列的和。)从头开始,遍历每一个数,开始第一重循环。对每一个数,又从头遍历到这个数的前一个数,这是第二重循环,在第二重循环中,用下标j表示当前遍历到的数,如果data[i]>data[j],则说明data[j]和data[i]能构成一个上升子序列,但此时还需继续往后遍历(因为要求最长),用tem保存最大的sum[j](到第j个数时的解,最大的sum[j]才能保证最长子序列)。遍历完后,将此时的sum[i]更新(sum[i]+=data[i]+tem),解决了当前的子问题。
3.AC代码
#include<iostream>
#include <string.h>
#include <algorithm>
using namespace std;
int a[1005], dp[1005];
const int inf = 999999999;
int main()
{
int n, i,j, ans;
while (cin>>n, n)
{
memset(dp, 0, sizeof(dp));
for (i = 1; i <= n; i++)
{
cin >> a[i];
}
for (i = 1; i <= n; i++)
{
ans = -inf;
for (j = 0; j<i; j++)
{
if (a[i] > a[j])
{
ans = max(ans, dp[j]);
}
}
dp[i] = ans + a[i];
}
ans = -inf;
for (i = 0; i <= n; i++)
{
if (dp[i]>ans)
ans = dp[i];
}
cout<<ans<<endl;
}
return 0;
}