zoukankan      html  css  js  c++  java
  • 【动态规划】POJ-3176

    一、题目

    Description

    The cows don't use actual bowling balls when they go bowling. They each take a number (in the range 0..99), though, and line up in a standard bowling-pin-like triangle like this:

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

    Then the other cows traverse the triangle starting from its tip and moving "down" to one of the two diagonally adjacent cows until the "bottom" row is reached. The cow's score is the sum of the numbers of the cows visited along the way. The cow with the highest score wins that frame.

    Given a triangle with N (1 <= N <= 350) rows, determine the highest possible sum achievable.

    Input

    Line 1: A single integer, N

    Lines 2..N+1: Line i+1 contains i space-separated integers that represent row i of the triangle.

    Output

    Line 1: The largest sum achievable using the traversal rules

    Sample Input

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

    Sample Output

    30
    Hint

    Explanation of the sample:

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

    The highest score is achievable by traversing the cows as shown above.

    二、思路&心得

    ​简单的动态规划问题,从底向上依次扫描就行了,可以用直接用DP,也可以用记忆化搜索。

    三、代码

    1.DP:

    #include<cstdio>
    #include<algorithm>
    using namespace std;
    const int MAX_N = 355;
    
    int N;
    int dp[MAX_N][MAX_N];
    
    void solve() {
    	for (int i = 0; i < N; i ++) {
    		for (int j = 0; j <= i; j ++) {
    			scanf("%d", &dp[i][j]);			
    		}
    	}
    	for (int i = N - 2; i >=0; i --) {
    		for (int j = 0; j <= i; j ++) {
    			dp[i][j] += max(dp[i + 1][j], dp[i + 1][j + 1]);
    		}
    	}
    	printf("%d
    ", dp[0][0]);
    }
    
    int main() {
    	while (~scanf("%d", &N)) {
    		solve();
    	}
    	return 0;
    }
    

    2.记忆化搜索:

    #include<cstdio>
    #include<algorithm>
    using namespace std;
    const int MAX_N = 355;
    
    int N;
    int dp[MAX_N][MAX_N];
    int visit[MAX_N][MAX_N];
    
    int score(int x, int y) {
    	if (visit[x][y] == 1) return dp[x][y];
    	visit[x][y] = 1;
    	if (x == N - 1) return dp[x][y];
    	return dp[x][y] += max(score(x + 1, y), score(x + 1, y + 1));
    }
    
    void solve() {
    	for (int i = 0; i < N; i ++) {
    		for (int j = 0; j <= i; j ++) {
    			scanf("%d", &dp[i][j]);			
    		}
    	}
    	printf("%d
    ", score(0, 0));
    }
    
    int main() {
    	while (~scanf("%d", &N)) {
    		solve();
    	}
    	return 0;
    }
    
  • 相关阅读:
    给自己一个书单
    pureMVC学习之一
    泛型与无聊
    队列与DelphiXe新语法
    有道理的前端
    具备 jQuery 经验的人如何学习AngularJS(附:学习路径)
    Blogging with github Pages
    Cookie/Session机制
    通往全栈工程师的捷径 —— react
    女生应该找个有独立博客的男朋友
  • 原文地址:https://www.cnblogs.com/CSLaker/p/7398183.html
Copyright © 2011-2022 走看看