2017.12.24
简单的动态规划
1.数字三角形(算法引入)
题目描述:下图所示是一个数字三角形,其中三角形中的数值为正整数,现规定从最顶层往下走到最底层,每一步可沿左斜线向下或右斜线向下走。设三角形有n层,编程计算出从顶层到底层的一条路径,使得该路径上的和最大,输出最大值。(n<=100)
思路&&代码(搜索回溯):
#include <stdio.h>
#include <math.h>
#include <string.h>
int map[101][101],n;
int count=0,ans=-20180101;
void search(int x,int y){
count+=map[x][y];
if(x==n){
if(count>ans)ans=count;
}
else{
search(x+1,y+1);
search(x+1,y);
}
count-=map[x][y];
}
int main(){
scanf("%d",&n);
int i,j;
for(i=1;i<=n;i++){
for(j=1;j<=i;j++){
scanf("%d",&map[i][j]);
}
}
search(1,1);
printf("%d\n",ans);
return 0;
}
思路&&代码(分治法):
#include <stdio.h>
#include <math.h>
#include <string.h>
int n,map[101][101];
int fenzhi(int x,int y){
if(x==n)return map[x][y];
int zi1,zi2,_max;
zi1=fenzhi(x+1,y);
zi2=fenzhi(x+1,y+1);
if(zi1<=zi2)_max=zi2;
else _max=zi1;
return _max+map[x][y];
}
int main(){
scanf("%d",&n);
int i,j;
for(i=1;i<=n;i++){
for(j=1;j<=i;j++){
scanf("%d",&map[i][j]);
}
}
printf("%d",fenzhi(1,1));
return 0;
}
思路&&代码(记忆化):
#include <stdio.h>
#include <math.h>
#include <string.h>
int map[101][101],book[101][101];
int n;
int max(int x,int y){
if(y>x)
return y;
else
return x;
}
int search(int r,int c){
int ans;
if (r==n) return map[r][c];
if (book[r+1][c]==-1)
book[r+1][c]=search(r+1,c);
if (book[r+1][c+1]==-1)
book[r+1][c+1]=search(r+1,c+1);
ans=max(book[r+1][c],book[r+1][c+1])+book[r][c];
return ans;
}
int main(){
scanf("%d",&n);
int i,j;
for(i=1;i<=n;i++){
for(j=1;j<=i;j++){
scanf("%d",&map[i][j]);
book[i][j]=-1;
}
}
printf("%d",search(1,1));
return 0;
}
思路&&代码(动态规划):
#include <stdio.h>
#include <math.h>
#include <string.h>
int map[101][101],book[101][101];
int max(int x,int y){
if(x>y)return x;
else return y;
}
int main(){
int n;
scanf("%d",&n);
int i,j;
for(i=1;i<=n;i++){
for(j=1;j<=i;j++){
scanf("%d",&map[i][j]);
}
}
for(j=1;j<=n;j++)
book[n][j]=map[n][j];
for(i=n-1;i>=1;i--)
for(j=1;j<=i;j++)
book[i][j]=max(book[i+1][j+1],book[i+1][j])+map[i][j];
printf("%d",book[1][1]);
return 0;
}
2.最长上升子序列(老师别急,我还没有做完,做完就会补上的)
思路:
核心代码:
状态: