POJ1651 Multiplication Puzzle(区间DP+记忆化搜索)
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 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
If he would take the cards in the opposite order, i.e. 50, then 20, then 1, the score would be
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
总算遇到一道比较水的区间DP了,这个题和矩阵最优链乘有点相似。首先倒着分析,最后一次操作时肯定只有三个数,即左右两个固定的数和上一次操作剩下的一个数。至于这个数选哪个,就要枚举left+1~right-1,这就是进行决策的过程,选完数后考虑应该从怎么转移过来,大脑里模拟一下过程,就能推出转移方程dp[l][r]=min(dp[l][r],process(l,i)+process(i,r)+a[i]*a[l]*a[r]);递归地求解,边界就是长度为2的话值为0,长度为3的话值为a[l]*a[l+1]*a[r],用DP数组存储。最后求的就是dp[1][n]。
#include <iostream> #include <cstdio> #include <cstring> using namespace std; int n,a[105],dp[105][105];//最后剩下的一定是左右两端的 int process(int l,int r) { if(l+1==r) { dp[l][r]=0; return 0; } if(l+2==r) { dp[l][r]=a[l]*a[l+1]*a[r]; return dp[l][r]; } int i; if(dp[l][r]!=0x3f3f3f3f)return dp[l][r]; for(i=l+1;i<=r-1;i++) { dp[l][r]=min(dp[l][r],process(l,i)+process(i,r)+a[i]*a[l]*a[r]); } return dp[l][r]; } int main() { cin>>n; int i; memset(dp,0x3f3f3f3f,sizeof(dp)); for(i=1;i<=n;i++)scanf("%d",&a[i]); cout<<process(1,n); return 0; }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!