Cod sursa(job #742259)

Utilizator PetcuIoanPetcu Ioan Vlad PetcuIoan Data 29 aprilie 2012 10:45:42
Problema Parantezare optima de matrici Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.04 kb
#include<stdio.h>
#include<assert.h>

#include<algorithm>
#include<vector>

using namespace std;

struct mat{
  long long h, w;

  mat(){};
};

const int knmax = 505;
long long matrixes, sol, dp[knmax][knmax];
mat given[knmax];

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

  scanf("%lld", &matrixes);

  for(int i = 1; i <= matrixes; ++i)
    scanf("%lld", &given[i].h);

  scanf("%lld", &given[matrixes].w);

  for(int i = 1; i < matrixes; ++i)
    given[i].w = given[i + 1].h;
}

void compute(int x, int y){
  if(x == y)
    return ;

  if(dp[x][y])
    return ;

  compute(x + 1, y);
  dp[x][y] = given[x].h * given[x].w * given[y].w + dp[x + 1][y];

  for(int i = x + 1; i <= y; ++i){
    compute(x, i - 1);
    compute(i, y);

    dp[x][y] = min(dp[x][y], dp[x][i - 1] + dp[i][y] + given[x].h * given[i].h * given[y].w);
  }

  return ;
}

void solve(){
  compute(1, matrixes);
  sol = dp[1][matrixes];
}

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

  printf("%lld", sol);
}

int main(){
  read();
  solve();
  write();
  return 0;
}