標籤:des style blog http color 使用
先上題目:
Multiplication Puzzle
| Time Limit: 1000MS |
|
Memory Limit: 65536K |
| Total Submissions: 6162 |
|
Accepted: 3758 |
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
610 1 50 50 20 5
Sample Output
3650
題意:給出一串數字,然後給你一種操作,選擇非邊緣的那兩個數位數字,然後獲得值為這個數字與其左右兩個數一共三個數的乘積的得分,然後被選的那個數消失,問最終只剩下兩個數的時候總得分什麼時候最大。
這一題是區間DP,我們可以枚舉某一個數,然後求如果最終是這個數消失的話能得到的最大得分是多少就可以了。
狀態轉移方程:dp[i][j][k]=max(dp[i][j][k],(i+1~j-1的最值) + (j+1~k-1的最值) +i*j*k)
這裡使用dfs來求值比較方便,而且遞迴的深度不會很長,所以不用擔心爆棧或者時間的問題。
這裡使用遞迴的方法實現的另一個原因的因為我平時寫DP比較習慣用遞推的形式,但是只掌握一種實現方式還是不夠,畢竟不同的情況用不同的實現方式會有不一樣的效果。
上代碼:
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <algorithm> 5 #define MAX 102 6 #define LL long long 7 using namespace std; 8 9 const int limit = 100000002;10 int p[MAX];11 int dp[MAX][MAX][MAX];12 int n;13 14 int dfs(int a,int b,int c){15 int minn=limit;16 if(dp[a][b][c]!=-1) return dp[a][b][c];17 dp[a][b][c]=p[a]*p[b]*p[c];18 for(int i=a+1;i<b;i++){19 dfs(a,i,b);20 minn = min(minn,dp[a][i][b]);21 }22 if(a+1<b) dp[a][b][c]+=minn;23 minn = limit;24 for(int i=b+1;i<c;i++){25 dfs(b,i,c);26 minn = min(minn,dp[b][i][c]);27 }28 if(b+1<c) dp[a][b][c]+=minn;29 return dp[a][b][c];30 }31 32 int main()33 {34 int sum;35 //freopen("data.txt","r",stdin);36 while(~scanf("%d",&n)){37 for(int i=1;i<=n;i++) scanf("%d",&p[i]);38 memset(dp,-1,sizeof(dp));39 sum=limit;40 for(int i=2;i<n;i++){41 dfs(1,i,n);42 sum = min(sum,dp[1][i][n]);43 }44 printf("%d\n",sum);45 }46 return 0;47 }1651