算法设计与分析3-4 数字三角形问题

  • 这个问题51Nod上面有可以提交的地方,题目意思很简单,不再仔细分析,自顶向下分析更加容易,所以考虑自顶向下求解,
    首先考虑搜索,从最顶上开始搜索它下面紧挨着的两个位置,递归搜索求取最大值,程序如下
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <vector>
#include <cmath>
#include <queue>
#include <stack>
#include <map>
using namespace std;
typedef long long ll;
const int INF = 0x3f3f3f3f;
const int MAXN = 1e6 + 100;
const double eps = 1e-6;
int Data[MAXN];
int tower[1000][1000];
int dp[1000][1000];
int ans;
int dfs(int x, int y, int n){
    
    
    if(x == n){
    
    
        return tower[x][y];
    }
    return tower[x][y] + max(dfs(x + 1, y, n), dfs(x + 1, y + 1, n));
}
int main(){
    
    
    // freopen("input.txt", "r", stdin);
    // freopen("output.txt", "w", stdout);
    int n;
    cin >> n;
    for(int i=1;i<=n;i++){
    
    
        for(int j=1;j<=i;j++){
    
    
            cin >> tower[i][j];
        }
    }
    cout << dfs(1, 1, n);
    return 0;
}
  • 在n比较大的时候时间很慢,考虑记忆化搜索,用数组存一下
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <vector>
#include <cmath>
#include <queue>
#include <stack>
#include <map>
using namespace std;
typedef long long ll;
const int INF = 0x3f3f3f3f;
const int MAXN = 1e6 + 100;
const double eps = 1e-6;
int Data[MAXN];
int tower[1000][1000];
int dp[1000][1000];
int ans;
int dfs(int x, int y, int n){
    
    
    if(dp[x][y]) return dp[x][y];
    if(x == n){
    
    
        return tower[x][y];
    }
    return dp[x][y] = tower[x][y] + max(dfs(x + 1, y, n), dfs(x + 1, y + 1, n));
}
int main(){
    
    
    // freopen("input.txt", "r", stdin);
    // freopen("output.txt", "w", stdout);
    int n;
    cin >> n;
    for(int i=1;i<=n;i++){
    
    
        for(int j=1;j<=i;j++){
    
    
            cin >> tower[i][j];
        }
    }
    cout << dfs(1, 1, n);
    return 0;
}

时间就很好了

  • 上面是递归的方法,现在考虑递推, d p [ i ] [ j ] dp[i][j] dp[i][j]可以从 d p [ i − 1 ] [ j ] dp[i-1][j] dp[i1][j] d p [ i − 1 ] [ j − 1 ] dp[i-1][j-1] dp[i1][j1]两个方向转移过来,取最大值不断更新即可
#include <iostream>
using namespace std;
int tower[505][505];
int main(){
    
    
    int n;
    cin >> n;
    for(int i=1;i<=n;i++){
    
    
        for(int j=1;j<=i;j++){
    
    
            cin >> tower[i][j];
        }
    }
    int ans = 0;
    for(int i=1;i<=n;i++){
    
    
        for(int j=1;j<=i;j++){
    
    
            tower[i][j] += max(tower[i - 1][j], tower[i - 1][j - 1]);
            ans = max(ans, tower[i][j]);
        }
    }
    cout << ans;
    return 0;
}
  • 我怎么也想不通这么简单的一道题在习题解答里面居然能写的那么晦涩难懂,实在难以理解,所以写一下

猜你喜欢

转载自blog.csdn.net/roadtohacker/article/details/115382413