[Review] NOIP exam topics Luogu P1040

Thinking

The first question looks like a tree, but in fact we can take it directly as a range of DP. make fi,j Storage interval [i,j] Plus the maximum, then the triple loop are enumerated left point, right point and the intermediate element, no cerebral circulation out f1,n That is [1,n] The maximum points in the interval. In the calculation process, each recording bit position of each node, a second Q output convenient.

Code

#include <cctype>
#include <climits>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <queue>
#include <utility>

int nextInt()
{
    int num = 0;
    char c;
    bool flag = false;
    while ((c = std::getchar()) == ' ' || c == '\r' || c == '\t' || c == '\n');
    if (c == '-')
        flag = true;
    else
        num = c - 48;
    while (std::isdigit(c = std::getchar()))
        num = num * 10 + c - 48;
    return (flag ? -1 : 1) * num;
}

typedef long long LL;

LL n, f[31][31] = { 0 }, i, j, k, x, a[31] = { 0 }, node[31][31] = { 0 };

void LTR(const int l, const int r)
{
    if (l > r)
        return;
    std::cout << node[l][r] << ' ';
    LTR(l, node[l][r] - 1);
    LTR(node[l][r] + 1, r);
}

int main(int argc, char **argv)
{
    int n = nextInt();
    for (int i = 0; i <= n; i++)
        for (int j = 0; j <= n; j++)
            f[i][j] = 1;
    for (int i = 1; i <= n; i++)
    {
        a[i] = nextInt();
        f[i][i] = a[i];
        node[i][i] = i;
    }
    for (int i = n - 1; i >= 1; i--)
        for (int j = i + 1; j <= n; j++)
            for (int k = i; k <= j; k++)
                if (f[i][k - 1] * f[k + 1][j] + a[k] > f[i][j])
                {
                    node[i][j] = k;
                    f[i][j] = f[i][k - 1] * f[k + 1][j] + a[k];
                }
    std::cout << f[1][n] << std::endl;
    LTR(1, n);
#ifdef __EDWARD_EDIT
    std::cin.get();
    std::cin.get();
#endif
    return 0;
}
Published 40 original articles · won praise 0 · Views 5149

Guess you like

Origin blog.csdn.net/edward00324258/article/details/78392635