什么是动态规划
20世纪50年代初美国数学家R.E.Bellman(理查德.贝尔曼)等人在研究多阶段决策过程(multistep decision process)的优化问题时,提出了著名的最优化原理(principle of optimality),把多阶段过程转化为一系列单阶段问题,逐个求解,创立了解决这类过程优化问题的新方法——动态规划(Dynamic Programming)。
动态规划,其实就是将整个问题划分为许多子问题,然后对每个子问题作出决策。
基础动态规划
数字三角形
题目链接: https://www.luogu.com.cn/problem/P1216
7
3 8
8 1 0
2 7 4 4
4 5 2 6 5
针对如上这个例子,我们如果按照贪心的思路,是(7→8→1→7→5),算出来是(28)。而(7→3→8→7→5)的结果为(30)。所以贪心是行不通的。
设置状态
定义(f[i][j])为( ext{到达第}i ext{行第}j ext{列})的最大值。
转移方程
我们从最后一层开始,由下往上走,不难得出方程:(f[i-1][j] = max(f[i][j],f[i][j+1])+a[i-1][j])
背包dp
01背包
采药: https://www.luogu.com.cn/problem/P1048
确定状态:设(f[i][j])为前(i)株草药总价值不超过(j)所获最大价值。
方程: (f[i][j]=max(f[i][j],f[i-1][j-w[i]]+v[i]))
由于第一维什么用也没有,所以舍掉:
优化方程: (f[j]=max(f[j],f[j-v[i]]+c[i]))
最终答案为(f[t])
for(int i=1;i<=n;i++)
{
for(int j=t;j>=v[i];j--)
{
if(f[j - v[i]] + c[i] > f[j])f[j] = f[j - v[i]] + c[i];
}
}
坐标型动态规划
爬楼梯: https://www.lintcode.com/problem/climbing-stairs/description
确定状态:设(f[i])为到达第(i)级楼梯的方案
对于每一层楼梯,我们可以由前一层爬一楼或前两层爬两楼。
方程: (f[i]=f[i-1]+f[i-2])
单序列动态规划
最长上升子序列: https://www.lintcode.com/problem/longest-increasing-subsequence/description
确定状态: 设(f[i])为以第(i)个结尾的最长上升子序列的长度。
方程: (f[i]=max(f[i],f[j]+1)(a[i]>a[j]))
初值: (f[i]=1)
for(int i=1;i<=n;i++)
{
for(int j=1;j<i;j++)
{
if(a[i] > a[j])f[i] = max(f[i],f[j] + 1);
}
}
(End.)