【POJ-1651】解题报告(区间DP入门)
原始题目
Multiplication Puzzle
- Time Limit: 1000MS
- Memory Limit: 65536K
- Total Submissions: 13111
- Accepted: 8035
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 \le N \le 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
题目大意
- 抽卡片,分数每次增加所抽卡片以及其相邻两侧的卡片的数值。不允许抽第一个和最后一个,抽到最后仅剩下这两张卡片,求最小的分数。
解题思路
- 每个大区间的分数都由最后抽的一张牌分成两个小区间,区间dp问题
- 状态转移方程 \[dp[i][j]=min(dp[i][k]+dp[k][j]+a[i]*a[k]*a[j]) (i\leq k \leq j)\] # 解题代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58#include <vector>
#include <queue>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <algorithm>
//#include <bits/stdc++.h>
#define ms(i,a) memset((i),(a),sizeof(i))
#define rep(i,a,n) for (int i=a;i<n;i++)
#define per(i,a,n) for (int i=n-1;i>=a;i--)
#define pb push_back
#define mp make_pair
#define np next_permutation
#define all(x) x.begin(),x.end()
#define fi first
#define se second
#define SZ(x) ((int)(x).size())
#define INF 0x3f3f3f3f
using namespace std;
int n,t,m;
int dp[105][105],a[105],sum[105]; //前缀和
void initial(){
ms(dp,0);
rep(i,1,n+1){
rep(j,i+2,n+1){
if(j==i+2) dp[i][j]=a[i]*a[i+1]*a[i+2];
else dp[i][j]=INF;
}
}
}
int main()
{
ios::sync_with_stdio(false);
// freopen("in.txt","r",stdin);
while(cin>>n)
{
sum[0]=0;
rep(i,1,n+1){
cin>>a[i];
// sum[i]=sum[i-1]+m;
}
initial();
for (int len = 4; len <= n; ++len){
for (int i = 1; i + len - 1 <= n; ++i) {
int j = i + len - 1;
for (int k = i; k <= j; ++k)
dp[i][j] = min(dp[i][j], dp[i][k] + dp[k][j] + a[i] * a[k] * a[j]);
// cout<<"i="<<i<<" j="<<j<<" dp="<<dp[i][j]<<endl;
}
}
cout<<dp[1][n]<<endl;
}
return 0;
}
收获与反思
- 注意边界条件
- 注意dp数组的初始化
本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!