Cod sursa(job #1007442)

Utilizator AlexandruValeanuAlexandru Valeanu AlexandruValeanu Data 8 octombrie 2013 22:02:13
Problema Parantezare optima de matrici Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.13 kb
#include <iostream>
#include <fstream>

using namespace std;

const int Nmax = 505;
const long long   oo = 1e15;

int N;
int A[Nmax];
long long M[Nmax][Nmax];

void read()
{
    freopen("podm.in", "r", stdin);

    scanf("%d", &N);

    for ( int i = 0; i <= N; ++i )
            scanf("%d", &A[i]);

    fclose( stdin );
}

void DP()
{
    for ( int n = 2; n <= N; ++n )
            for ( int i = 1; i <= N - n + 1; ++i )
            {
                int j = i + n - 1, position = 0;

                M[i][j] = oo;

                for ( int k = i; k < j; ++k )
                {
                    if ( M[i][j] > M[i][k] + M[k + 1][j] + 1LL * A[i - 1] * A[k] * A[j] )
                    {
                        M[i][j] = M[i][k] + M[k + 1][j] + 1LL * A[i - 1] * A[k] * A[j];
                        position = k;
                    }
                }

                M[j][i] = position;
            }
}

void print()
{
    freopen("podm.out", "w", stdout);

    printf("%lld\n", M[1][N]);

    fclose( stdout );
}

int main()
{
    read();
    DP();
    print();

    return 0;
}