MLE,不会压缩维度,求助

P1439 【模板】最长公共子序列

Swiftie_wyc22 @ 2022-03-13 19:35:43

#include <bits/stdc++.h>

using namespace std;

int n, a[100010], b[100010];
int f[10010][10010];

void dp()
{
    for (int i = 1; i <= n; i++)
        for (int j = 1; j <= n; j++)
            if (a[i - 1] == b[j - 1])
                f[i][j] = f[i - 1][j - 1] + 1;
            else
                if (f[i][j - 1] >= f[i - 1][j])
                    f[i][j] = f[i][j - 1];
                else
                    f[i][j] = f[i - 1][j];
}

int main()
{
    scanf("%d", &n);
    for (register int i = 0; i < n; i++)
        scanf("%d", &a[i]);
    for (register int i = 0; i < n; i++)
        scanf("%d", &b[i]);
    for (register int i = 0; i <= n; i++)
        f[i][0] = f[i][0] = 0;
    dp();
    cout << f[n][n] << endl;
    return 0;
}

怎么写成一维的数组呀?


by Amore_eterno @ 2022-03-13 19:48:01

@Aeterna


#include <bits/stdc++.h>

using namespace std;

int n, a[100010], b[100010];
int f[100010];

void dp()
{
    for (int i = 1; i <= n; i++)
        for (int j = 1; j <= n; j++)
            if (a[i - 1] == b[j - 1])
                f[j] = f[j - 1] + 1;
            else
                if (f[j - 1] >= f[j])
                    f[j] = f[j - 1];
                else
                    f[j] = f[j];
}

int main()
{
    scanf("%d", &n);
    for (register int i = 0; i < n; i++)
        scanf("%d", &a[i]);
    for (register int i = 0; i < n; i++)
        scanf("%d", &b[i]);
    f[0] = 0;
    dp();
    cout << f[n]<< endl;
    return 0;
}

但是超时


by Swiftie_wyc22 @ 2022-03-13 20:47:36

@Konnyaku41377 那怎么AC呀?题解我看不懂qwq,如果您有空能说说嘛?:D


|