[dp]POJ 3176 Cow Bowling解題報告

題目:
Cow Bowling
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 16077 Accepted: 10705
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.
Source
USACO 2005 December Bronze

方法一:從上往下dp

#include <iostream>
#include<cmath>
#include<cstring>
#include<cstdio>
using namespace std;
int dp[355][355];//dp[i][j]表示牛走到第i行第j個元素時路徑長度最大值
int main(){
    freopen("output.txt","w",stdout);
    freopen("input.txt","r",stdin);
    int N;
    scanf("%d",&N);
    for(int i=1;i<=N;i++){
        for(int j=1;j<=i;j++){
            scanf("%d",&dp[i][j]);
        }
    }
    for(int i=2;i<=N;i++){//每行最左邊和最右邊的單獨考慮
        dp[i][1]+=dp[i-1][1];
        dp[i][i]+=dp[i-1][i-1];
    }
    for(int i=2;i<=N;i++){//每行除了最左邊和最右邊,中間的部分
        for(int j=2;j<=i-1;j++){
            dp[i][j]+=max(dp[i-1][j-1],dp[i-1][j]);
        }
    }
    int ans=-1;
    for(int j=1;j<=N;j++)//在第N行找到最大值
        ans=max(ans,dp[N][j]);
    cout<<ans<<endl;
    return 0;
}

缺點:要單獨考慮左右兩邊,最後還要遍歷最後一行尋找結果。

方法二:從下往上dp,最後dp[1][1]就是答案。
優點:不用考慮特殊元素,過程簡單明瞭
原理:原題是從上往下找權值最大的路徑。因爲這條路徑如果存在,那麼路徑是可逆的,等效於從最下面找到達最上面的權值最大的路徑,即從下往上dp。

#include <iostream>
#include<cmath>
#include<cstring>
#include<cstdio>
#define MAXN  70000
using namespace std;
int dp[355][355];
int main(){
    freopen("output.txt","w",stdout);
    freopen("input.txt","r",stdin);
    int N;
    scanf("%d",&N);
    for(int i=1;i<=N;i++){
        for(int j=1;j<=i;j++){
            scanf("%d",&dp[i][j]);
        }
    }
    for(int i=N-1;i>=1;i--){
        for(int j=1;j<=i;j++){
            dp[i][j]+=max(dp[i+1][j],dp[i+1][j+1]);
        }
    }
    cout<<dp[1][1]<<endl;
    return 0;
}

歡迎留言,積極討論,一起進步!

發佈了77 篇原創文章 · 獲贊 22 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章