avatar
fireworks99
keep hungry keep foolish

SDNU 1330 Max Sum

最大上升子序列(模板)

Description

给定长度为n的正整数序列a1,a2,…,an。

令sum=ab1+ab2+…+abm,并且满足:ab1<ab2<…<abm;b1<b2<…<bm;1<=m<=n。

求最大的sum。

#include <cstdio>
#include <iostream>
#include <algorithm>
using namespace std;

int a[1005];
long long sum[1005];

int main()
{
    int n;
    while(~scanf("%d", &n))
    {
        sum[0] = a[0] = 0;
        for(int i = 1; i <= n; ++i)
        {
            scanf("%d", &a[i]);
            sum[i] = a[i];
        }

        for(int i = 1; i <= n; ++i)
        {
            long long tem = sum[i];
            for(int j = i - 1; j >= 1; --j)
                if(a[j] < a[i])
                tem = max(tem, sum[j] + a[i]);///想清楚,非 sum[i] + a[j]
            sum[i] = tem;
        }

        long long ans = 0;
        for(int i = 1; i <= n; ++i)
            ans = max(ans, sum[i]);
        cout << ans << '\n';
    }
    return 0;
}
Site by Baole Zhao | Powered by Hexo | theme PreciousJoy