Algorithms/Dynamic Programming/Matrix-chain Multiplication Problem

Last-modified: 2008-05-23 (金) 11:03:19

Matrix-chain Multiplication Problem

連鎖行列積問題

Program

#include
#include

#define

using namespace std;

int cost[MAX][MAX], best[MAX][MAX], data[MAX];
int n, temp;

void order(int i, int j) {
  if(i == j) {
    cout << "A" << i;
  } else {
    cout << "(";
    order(i, best[i][j] - 1);

    cout << " x ";

    order(best[i][j], j);
    cout << ")";
  }
}

void func() {
  for(int i = 1 ; i <= n ; i++) {
    for(int j = i + 1 ; j <= n ; j++) {
      cost[i][j] = INT_MAX;
    }
  }

  for(int i = 1 ; i <= n ; i++) {
    cost[i][i] = 0;
  }

  for(int j = 1 ; j < n ; j++) {
    for(int i = 1 ; i <= n - j ; i++) {
      for(int k = i + 1 ; k <= i + j ; k++) {
        temp = cost[i][k - 1] + cost[k][i + j] + data[i] * data[k] * data[i + j + 1];

        if(temp < cost[i][i + j]) {
          cost[i][i + j] = temp;
          best[i][i + j] = k;
        }
      }
    }
  }

  order(1, n);

  cout << endl;
}