第五讲 动态规划
目錄
- 背包問題
- 01背包【簡單】
- 完全背包【一般】
- 多重背包問題【一般】
- 分組背包問題【一般】
- 線性DP
- 898. 數字三角形【一般】
- 895. 最長上升子序列【一般】
- 896. 最長上升子序列 II【中】
- 895. 最長公共子序列【中】
- 902. 最短編輯距離【中】
- 899. 編輯距離【中】
- 區間DP
- 282. 石子合并【中】
- 計數類DP【一般】
- 狀壓DP
- 291. 蒙德里安的夢想
- 91. 最短Hamilton路徑
- 樹形DP
- 285. 沒有上司的舞會
- 記憶化搜索
- 901. 滑雪
背包問題
01背包: 每件物品最多只用一次
完全背包: 每件物品有無限個
多重背包 : 每件物品有不同多個
分組背包 : 有多個組,每組內有多個物品,每一個組內只能選一個
01背包【簡單】
01背包問題模板題
完全背包【一般】
完全背包問題板子題
多重背包問題【一般】
多重背包板子題
分組背包問題【一般】
分組背包問題板子題
線性DP
898. 數字三角形【一般】
898. 數字三角形
895. 最長上升子序列【一般】
895. 最長上升子序列
896. 最長上升子序列 II【中】
896. 最長上升子序列 II
895. 最長公共子序列【中】
897. 最長公共子序列
902. 最短編輯距離【中】
902. 最短編輯距離
899. 編輯距離【中】
899. 編輯距離
區間DP
282. 石子合并【中】
282. 石子合并
計數類DP【一般】
900. 整數劃分
狀壓DP
291. 蒙德里安的夢想
91. 最短Hamilton路徑
樹形DP
285. 沒有上司的舞會
#include<bits/stdc++.h> using namespace std; const int N=1e5+10; int h[N],e[N],ne[N],idx; int happy[N],st[N],n; int f[N][2]; //f[u][0]表示以u為根且不選u //f[u][1]表示以u為根且選u void add(int a,int b) {e[idx]=b,ne[idx]=h[a],h[a]=idx++; } void dfs(int u) {f[u][1]+=happy[u];for(int i=h[u];i!=-1;i=ne[i]){int j=e[i];dfs(j);f[u][0]+=max(f[j][1],f[j][0]);f[u][1]+=f[j][0];} } int main(void) {memset(h,-1,sizeof h);cin>>n;for(int i=1;i<=n;i++) cin>>happy[i];for(int i=1;i<=n-1;i++){int a,b; cin>>a>>b;add(b,a);st[a]++;}int root=1;while(st[root]) root++;dfs(root);cout<<max(f[root][0],f[root][1]);return 0; }記憶化搜索
901. 滑雪
#include<bits/stdc++.h> using namespace std; const int N=310; int f[N][N],a[N][N],n,m; int dx[4]={-1,0,0,1}; int dy[4]={0,-1,1,0}; int dp(int x,int y) {if(f[x][y]!=-1) return f[x][y];f[x][y]=1;for(int i=0;i<4;i++){int tempx=x+dx[i],tempy=y+dy[i];if(tempx>=1&&tempx<=n&&tempy>=1&&tempy<=m&&a[tempx][tempy]<a[x][y])f[x][y]=max(f[x][y],dp(tempx,tempy)+1);}return f[x][y]; } int main(void) {memset(f,-1,sizeof f);cin>>n>>m;for(int i=1;i<=n;i++)for(int j=1;j<=m;j++)cin>>a[i][j];int res=0;for(int i=1;i<=n;i++)for(int j=1;j<=m;j++)res=max(res,dp(i,j));cout<<res;return 0; }總結
- 上一篇: 第三章 搜索与图论 【完结】
- 下一篇: 第六章 贪心 【完结】