Cod sursa(job #3347507)

Utilizator Sabin1133Padurariu Sabin Sabin1133 Data 16 martie 2026 21:36:04
Problema Parantezare optima de matrici Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.19 kb
#include <iostream>

#define NMAX 500
#define MCMMAX(n) ((n * (n + 1)) / 2)

int mcm_hash(int first, int second, int total)
{
    int total_delta = total - (second - first + 1);

    return ((total_delta * (total_delta + 1)) / 2) + first - 1;
}

int main()
{
    int n;
    int d[NMAX + 1];
    long long multpls, m[MCMMAX(NMAX)];

    freopen("podm.in", "r", stdin);
    freopen("podm.out", "w", stdout);

    std::cin >> n;

    for (int i = 0; i <= n; ++i)
        std::cin >> d[i];

    for (int i = 1; i <= n; ++i)
        m[mcm_hash(i, i, n)] = 0;

    for (int i = 1; i < n; ++i)
        m[mcm_hash(i, i + 1, n)] = 1LL * d[i - 1] * d[i] * d[i + 1];

    for (int delta = 2; delta < n; ++delta)
        for (int i = 1, j = i + delta; j <= n; ++i, ++j) {
            multpls = m[mcm_hash(i, i, n)] + m[mcm_hash(i + 1, j, n)] + 1LL * d[i - 1] * d[i] * d[j];

            for (int k = i + 1; k < j; ++k)
                multpls = std::min(
                    multpls,
                    m[mcm_hash(i, k, n)] + m[mcm_hash(k + 1, j, n)] + 1LL * d[i - 1] * d[k] * d[j]
                );

            m[mcm_hash(i, j, n)] = multpls;
        }
            

    std::cout << m[mcm_hash(1, n, n)] << '\n';

    return 0;
}