码迷,mamicode.com
首页 > 其他好文 > 详细

动态规划-记忆化搜索

时间:2018-02-10 14:02:07      阅读:192      评论:0      收藏:0      [点我收藏+]

标签:学习   sdn   mem   for   using   ring   ide   stdio.h   ++   

1.数字三角形

学习链接:http://blog.csdn.net/zwhlxl/article/details/46225947

输入样例:

5
7
3 8
8 1 0
2 7 4 4
4 5 2 6 5

输出样例:

30

递归代码:

技术分享图片
#include <stdio.h>
#include <memory.h>
#include <math.h>
#include <string>
#include <vector>
#include <set>
#include <stack>
#include <queue>
#include <algorithm>
#include <map>


#define I scanf
#define OL puts
#define O printf
#define F(a,b,c) for(a=b;a<c;a++)
#define FF(a,b) for(a=0;a<b;a++)
#define FG(a,b) for(a=b-1;a>=0;a--)
#define LEN 101
#define MAX 1<<30
#define V vector<int>

using namespace std;

int num[LEN][LEN]; 
int dp[LEN][LEN];
int n;

int getMax(int i,int j){
    if(dp[i][j]>=0) return dp[i][j]; 
    if(i==n) return num[i][j];
    int a=getMax(i+1,j);
    int b=getMax(i+1,j+1);
    dp[i][j]=max(a,b)+num[i][j];
    return dp[i][j];
}

int main(){
    freopen("数字三角形.txt","r",stdin);
    int i,j;
    scanf("%d",&n);
    for(i=1;i<=n;i++){
        for(j=1;j<=i;j++){
            I("%d",&num[i][j]);
        }
    }
    for(i=1;i<=n;i++)
        fill(dp[i],dp[i]+1+n,-1);
    printf("%d",getMax(1,1));
    return 0;
}
View Code

循环代码:

技术分享图片
#include <stdio.h>
#include <memory.h>
#include <math.h>
#include <string>
#include <vector>
#include <set>
#include <stack>
#include <queue>
#include <algorithm>
#include <map>

#define I scanf
#define OL puts
#define O printf
#define F(a,b,c) for(a=b;a<c;a++)
#define FF(a,b) for(a=0;a<b;a++)
#define FG(a,b) for(a=b-1;a>=0;a--)
#define LEN 101
#define MAX 1<<30
#define V vector<int>

using namespace std;

int num[LEN][LEN]; 
int dp[LEN][LEN];
int n;

int main(){
    freopen("数字三角形.txt","r",stdin);
    int i,j;
    scanf("%d",&n);
    for(i=1;i<=n;i++){
        for(j=1;j<=i;j++){
            I("%d",&num[i][j]);
        }
    }
    for(i=1;i<=n;i++)
        dp[n][i]=num[n][i];
    for(i=n-1;i>=1;i--){
        for(j=1;j<=i;j++){
            dp[i][j]=max(dp[i+1][j],dp[i+1][j+1])+num[i][j];
        }
    }
    printf("%d",dp[1][1]);
    return 0;
}
View Code

 


 

动态规划-记忆化搜索

标签:学习   sdn   mem   for   using   ring   ide   stdio.h   ++   

原文地址:https://www.cnblogs.com/TQCAI/p/8438424.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!