zoukankan      html  css  js  c++  java
  • csu1022 菜鸟和大牛 dp

    第一次做dp, 一次就ac了, 体验了一把大牛的感觉。。

    题目描述:

    一个由n行数字组成的三角形,第i行有2i-1个正整数(小于等于1000),如下:

             3

          7 1 4

       2 4 3 6 2

    8 5 2 9 3 6 2

    要求你用笔从第1行画到第n(0 < n ≤ 100)行,从当前行往下画的时候只能在相邻的数字经过,也就是说,如果从一行的一个数往下画,只能选择其左下或者正下或者右下三个数中的一个(如果存在的话),把所有被画起来的数字相加,得到一个和,求能得到的最大的和的值是多少。

    上例中能得到的最大的和为3 + 7 + 4 + 9 = 23.

    // 1022 dp
    # include <stdio.h>
    # include <string.h>
    # define MAXN 10005
    int max(int a, int b, int c);
    int main()
    {
    int a[MAXN], T, n;
    int i, j, tmp, end, up, low;
    int r, s, t, ans;
    scanf("%d", &T);
    while (T > 0)
    {
    scanf("%d", &n);
    ans = 0;
    tmp = n*n+1;
    for (i=1; i<tmp; ++i)
    scanf("%d", &a[i]);
    for (i=2; i<=n; ++i)
    {
    end = i*i+1;
    up = (i-1)*(i-1)+1;
    low = (i-2)*(i-2);
    for(j = up; j < end; ++j)
    {
    r = s = t = 0;
    tmp = j-2*i+1;
    if(tmp<up && tmp>low)
    r = a[tmp];
    if(tmp+1<up && tmp+1>low)
    s = a[tmp+1];
    if(tmp+2<up && tmp+2>low)
    t = a[tmp+2];
    a[j] += max(r, s, t);
    }
    }
    for (i = (n-1)*(n-1)+1; i < n*n+1; ++i)
    if(ans < a[i]) ans = a[i];
    printf("%d\n", ans);
    --T;
    }
    return 0;
    }
    int max(int a, int b, int c)
    {
    int t;
    t = (a>b ? a:b);
    if (t < c) t = c;
    return t;
    }
  • 相关阅读:
    python学习6—数据类型之集合与字符串格式化
    python学习5—一些关于基本数据结构的练习题
    21-python-time,random模块的应用
    20-python-装饰器⭐
    19-python-迭代器、生成器
    18-python-文件的操作
    17-python-主要内置函数
    16-python-map、filter函数
    15-python-局部变量全局变量
    14-python-函数
  • 原文地址:https://www.cnblogs.com/JMDWQ/p/2356729.html
Copyright © 2011-2022 走看看