Cod sursa(job #3274199)

Utilizator nusuntvictorVictor Stefan nusuntvictor Data 5 februarie 2025 18:06:59
Problema Parantezare optima de matrici Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.67 kb
#include <bits/stdc++.h>
#define INF 0x3f3f3f3f
using namespace std;

ifstream fin("podm.in");
ofstream fout("podm.out");

long long n, p[502], dp[502][502];

long long sol(int i, int j) {
    if (i == j) return 0; // Cost 0 pentru o singură matrice
    if (dp[i][j] != INF) return dp[i][j];

    long long ans = INF;
    for (int m = i; m < j; ++m) {
        ans = min(ans, sol(i, m) + sol(m + 1, j) + p[i] * p[m + 1] * p[j + 1]);
    }

    dp[i][j] = ans;
    return ans;
}

int main() {
    fin >> n;
    for (int i = 1; i <= n + 1; ++i)
        fin >> p[i];

    memset(dp, INF, sizeof(dp)); // Inițializare cu INF

    fout << sol(1, n) << '\n';
}