1. 程式人生 > >poj-1651-Multiplication Puzzle--區間DP

poj-1651-Multiplication Puzzle--區間DP

ger fine ace text arc pri efi play number

poj-1651-Multiplication Puzzle--區間DP

Multiplication Puzzle
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 10734 Accepted: 6704

Description

The multiplication puzzle is played with a row of cards, each containing a single positive integer. During the move player takes one card out of the row and scores the number of points equal to the product of the number on the card taken and the numbers on the cards on the left and on the right of it. It is not allowed to take out the first and the last card in the row. After the final move, only two cards are left in the row.

The goal is to take cards in such order as to minimize the total number of scored points.

For example, if cards in the row contain numbers 10 1 50 20 5, player might take a card with 1, then 20 and 50, scoring
10*1*50 + 50*20*5 + 10*50*5 = 500+5000+2500 = 8000

If he would take the cards in the opposite order, i.e. 50, then 20, then 1, the score would be
1*50*20 + 1*20*5 + 10*1*5 = 1000+100+50 = 1150.

Input

The first line of the input contains the number of cards N (3 <= N <= 100). The second line contains N integers in the range from 1 to 100, separated by spaces.

Output

Output must contain a single integer - the minimal score.

Sample Input

6
10 1 50 50 20 5

Sample Output

3650

Source

Northeastern Europe 2001, Far-Eastern Subregion

1651 Accepted 508K 0MS G++ 764B 2017-09-16 15:26:12

對於這種區間DP問題,主要是寫對DP方程式。開始寫成 dp[i][j] = dp[i][k-1] + num[k-1]*num[k]*num[k+1] + dp[k+1][j] . 明顯是沒有理解題意。

將該num[k] 給取出之後, num[k-1] 和 num[k+1] 成為相鄰的,所以:

不應該是需要從後面逆推,即是 dp[i][j] = dp[i][k] + dp[k][j] + num[i]*num[j]*num[k] . 可以從三個數字,四個數字這樣試下。

#include <cstdio> 
#include <cstring>

#define min(a, b) (a)>(b)?(b):(a) 
const int MAXN = 110; 

int n, num[MAXN]; 
long long dp[MAXN][MAXN]; 

long long Solve(int l, int r){
	if(dp[l][r] != 0x3f3f3f3f3f3f){
		return dp[l][r]; 
	}
	if(l + 1 >= r){
		dp[l][r] = 0; 
		return 0; 
	}
	for(int i=l+1; i<r; ++i){
		long long tmp = num[l]*num[i]*num[r]; 
		dp[l][r] = min(dp[l][r], tmp + Solve(l, i) + Solve(i, r)); 
	} 
	return dp[l][r]; 
}

int main(){
	freopen("in.txt", "r", stdin); 

	long long ans; 
	while(scanf("%d", &n) != EOF){
		for(int i=0; i<n; ++i){
			scanf("%d", &num[i]);  
		} 
		for(int i=0; i<n; ++i){
			for(int j=0; j<n; ++j){
				dp[i][j] = 0x3f3f3f3f3f3f; 
			}
		}
		// memset(dp, 0x3f3f3f3f, sizeof(dp));  
		ans = Solve(0, n-1); 
		printf("%lld\n", ans );
	} 
	return 0; 
}

  

poj-1651-Multiplication Puzzle--區間DP