AcWing 320. energy necklace

Topic links: Click here
Here Insert Picture Description
Here Insert Picture Description

And matrix continually multiply like.

f [ L , R ] f[L,R] represents all the [ L , R ] [L,R] were combined in a way to the maximum bead (matrix).

State transition equation:

f [ L , R ] = m a x ( f [ L , K ] + f [ K , R ] + w [ L ] w [ K ] w [ R ] ) f[L,R]=max(f[L,K]+f[K,R]+w[L]*w[K]*w[R])

Tip: split ring and chain copied doubled, the question becomes merge adjacent beads on the line, each with a length of n + 1 n+1 interval corresponds to a situation in a ring shape.

#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>

using namespace std;
const int N = 210;

int w[N];
int f[N][N];

int main()
{
    int n;
    scanf("%d", &n);
    for(int i = 1; i <= n; ++i)
    {
        scanf("%d", &w[i]);
        w[i + n] = w[i];
    }
    
    for(int len = 3; len <=  n + 1; len++)
    {
        for(int l = 1; l + len - 1 <= 2 * n; l++)
        {
            int r = l + len - 1;
            
            for(int k = l + 1; k < r; k++)
            {
                f[l][r] = max(f[l][r], f[l][k] + f[k][r] + w[l] * w[k] * w[r]);
            }
        }
    }
    
    int ans = 0;
    for(int i = 1; i <= n; ++i) ans = max(ans, f[i][i + n]);
    
    printf("%d\n", ans);
    
    return 0;
}
Published 844 original articles · won praise 135 · Views 150,000 +

Guess you like

Origin blog.csdn.net/qq_42815188/article/details/105022790