线性dp A(poj1163)

(http://poj.org/problem?id=1163)
The Triangle
Time Limit: 1000MS
Memory Limit: 10000K
Total Submissions: 30397
Accepted: 17973
Description
7
3 8
8 1 0
2 7 4 4
4 5 2 6 5

(Figure 1)
Figure 1 shows a number triangle. Write a program that calculates the highest sum of numbers passed on a route that starts at the top and ends somewhere on the base. Each step can go either diagonally down to the left or diagonally down to the right.
Input
Your program is to read from standard input. The first line contains one integer N: the number of rows in the triangle. The following N lines describe the data of the triangle. The number of rows in the triangle is > 1 but <= 100. The numbers in the triangle, all integers, are between 0 and 99.
Output
Your program is to write to standard output. The highest sum is written as an integer.
Sample Input
5
7
3 8
8 1 0
2 7 4 4
4 5 2 6 5
Sample Output
30
这个是自己的第一篇博客吧,格式什么的可能都会很粗糙。相信以后能越来越好~~
因为感觉做完题目不能老是就throw-away了,真的有些东西需要记录和总结自己才能在acm道路上越走越远。
开始自己是做纸质笔记和总结的,可是后来发现代码不抄上去笔记看着根本还是一头雾水,而把代码全部手抄上去又太麻烦。既然大家都说博客好那么就试一试咯。
进入正题,这道题是一道很经典的线性dp题目,大意是说求从上走到底能得到的最大分数。我们用a[i]代表每个节点分数,也即权值,dp[i][j]代表当走到第i行第j列(从0开始数)所能得到的最大分数,所以会发现dp[i][j] = max{dp[i - 1][j - 1], dp[i - 1][j]} + a[i],是上一步所能得到的最大分数加此点的分数。求解顺序自然是双重循环依次求dp[0][0], dp[1][0], dp[1][1]等,某行的每一个数据可以通过上一行的某些数据得到。
而答案则是最后一行中最大的一个分数,因此最后再把最后一行遍历一遍求出最大值就好了。
(在某巨巨的帮助下我终于学会了让代码自动显示行数,~~o(>_<)o ~~)
对了,下面的代码没有用dp,而用的sum。

#include 
#include 
#include 
using namespace std;

int a[105][105], sum[105][105];
int n;

int main()
{
    int answer = 0;
    cin >> n;
    for (int i = 0; i < n; i++)
    {
       for (int j = 0; j <= i; j++)
       {
           cin >> a[i][j];
       }
    }
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j <= i; j++)
        {
            if (i == 0 && j == 0) answer = sum[i][j] = a[i][j];
            else
            {
                sum[i][j] = max(sum[i - 1][j - 1], sum[i - 1][j]) + a[i][j];
                answer = max(answer, sum[i][j]);
            }
            //sum[i][j] = max(sum[i - 1][j - 1], sum[i - 1][j]) + a[i][j];
            //answer = max(answer, sum[i][j]);
        }
    }
    cout << answer << endl;
}

你可能感兴趣的:(acm,线性dp)