首页 > 专题系列 > Java解POJ > POJ 1651 Multiplication Puzzle [解题报告] Java
2013
11-10

POJ 1651 Multiplication Puzzle [解题报告] Java

Multiplication Puzzle

问题描述 :

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.

输入:

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 must contain a single integer – the minimal score.

样例输入:

6
10 1 50 50 20 5

样例输出:

3650

解题代码:

//* @author: [email protected]
import java.io.*;
public class Main
{
	public static void main(String[] args) throws NumberFormatException, IOException
	{
	 InputStreamReader is=new InputStreamReader(System.in);
	 BufferedReader in=new BufferedReader(is);
	 int a=Integer.parseInt(in.readLine());
	 int[] arr=new int[a];
	 String[] ss=in.readLine().split(" ");
	 for(int i=0;i< a;i++)
		arr[i]=Integer.parseInt(ss[i]);
	 int[][] gra=new int[a][a];
	 for(int i=2;i< a;i++)
	 {
	  for(int j=0;j+i< a;j++)
	   {
		int min=999999999,u=-1;
		for(int k=j+1;k< j+i;k++)
		{
		   u=gra[j][k]+gra[k][j+i]+arr[j]*arr[k]*arr[j+i];
		   if(min>u) min=u;
		}
		gra[j][j+i]=min;
	    }
	  }
	  System.out.println(gra[0][a-1]);
	}
}

  1. 如果两个序列的最后字符不匹配(即X [M-1]!= Y [N-1])
    L(X [0 .. M-1],Y [0 .. N-1])= MAX(L(X [0 .. M-2],Y [0 .. N-1]),L(X [0 .. M-1],Y [0 .. N-1])
    这里写错了吧。