洛谷 1063 能量项链

一个基础又经典的区间DP问题。。。。。

类似于石子归并,先破环为链,然后枚举区间长、左端点、中间点,n^3暴力搞就AC了。

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>

using namespace std;

int read()
{
    int x = 0;
    int k = 1;
    char c = getchar();
    
    while (c > '9' || c < '0') 
        if (c == '-') c = getchar(), k = -1;
        else c = getchar();
    while (c >= '0' && c <= '9')
        x = (x << 1) + (x << 3) + (c ^ 48),
        c = getchar();
    
    return x * k; 
}

int n;
int b[210][210];

struct node{
    int h;
    int t;
}a[210];

int main()
{
    n = read();
    int nn = n << 1;
    for (int i = 1; i <= nn; ++i) 
    {
        if (i <= n) a[i].h = read();
        else a[i].h = a[i - n].h;
        if (i != 1) a[i - 1].t = a[i].h;
    }
    for (int i = 1; i <= nn; ++i) b[i][i] = 0;
    
    for (int l = 1; l <= n; ++l)
        for (int i = 1, j = i + l; j <= nn; ++i, j = i + l)
            for (int k = i; k < j; ++k)
                b[i][j] = max(b[i][j], b[i][k] + b[k + 1][j] + a[i].h * a[k].t * a[j].t);
    
    int ans = -1;
    
    for (int i = 1; i <= n; ++i)
        ans = max(ans, b[i][i + n - 1]);
    
    printf("%d", ans);
    return 0;
}
原文地址:https://www.cnblogs.com/yanyiming10243247/p/9716955.html