零分求调

B3637 最长上升子序列

XiongYingHao @ 2024-01-20 15:17:34

#include <stdio.h>

int n, max;
int num[5005];
int dp[5005];

int main()
{
    scanf("%d", &n);
    for (int i = 0; i < n; i++)
    {
        scanf("%d", &num[i]);
        dp[i] = 1;
    }
    for (int i = 0; i < n; i++)
    {
        for (int j = i; j < n; j++)
        {
            if(num[j] < num[i])
                dp[i] = dp[i] > (dp[j] + 1) ? dp[i] : (dp[j] + 1);
        }
        if (dp[i] > max)
            max = dp[i];
    }
    printf("%d", max);
    return 0;
}

刚学动规的蒟蒻一枚


by bugmaker3243 @ 2024-01-20 15:25:08

@xiongpapa

我觉得你想写的可能是:

for (int i = 0; i < n; i++)
    for (int j = 0; j < i; j++)

而不是

for (int i = 0; i < n; i++)
    for (int j = i; j < n; j++)

by XiongYingHao @ 2024-01-20 15:29:57

@bugmaker3243 okok,过了,谢谢dalao,不过为啥是从0到i-1找比它小的而不是从i到n找比它大的,不是要找上升子序列吗


by bugmaker3243 @ 2024-01-20 15:42:42

@xiongpapa 但是你别的部分的意思是,寻找一个前面的比 a[i] 小的 a[j],用 dp[j] 来更新 dp[i],你说的另外一种写法也是对的,比如:

for (int i = 0; i < n; i++)
    {
        for (int j = i; j < n; j++)
        {
            if(num[j] > num[i])
                dp[j] = max(dp[j] , dp[i] + 1);
        }
        if (dp[i] > max)
            max = dp[i];
    }

by XiongYingHao @ 2024-01-20 17:04:50

@bugmaker3243 哦哦,我搞串了,谢谢dalao


|