zoukankan      html  css  js  c++  java
  • Poj 1163 The Triangle 之解题报告


    Time Limit: 1000MS   Memory Limit: 10000K
    Total Submissions: 42232   Accepted: 25527

    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

     

    对于这题若按照常规可能做不出来;但是用递推的思想就可以计算出来啦

    代码:

     

     1 #include<cstdio>
     2 #include<iostream>
     3 #include<algorithm>
     4 #include<cstring>
     5 
     6 using namespace std;
     7 
     8 const int maxn = 100+10;
     9 int vis[maxn][maxn];
    10 int Triangle[maxn][maxn];
    11 
    12 int max(int a,int b)
    13 {
    14     return a>b?a:b;
    15 }
    16 
    17 int main(void)
    18 {
    19     int i,j,n;
    20     while(~scanf("%d",&n))
    21     {
    22          for(i=1;i<=n;++i)
    23              for(j=1;j<=i;++j)
    24                  scanf("%d",&Triangle[i][j]);
    25          memset(vis,0,sizeof(vis));
    26          for(i=1;i<=n;++i)
    27          {
    28              for(j=1;j<=i;++j)
    29              {
    30                   if(i==1) vis[i][j]=Triangle[i][j];
    31                   else if(j==1) vis[i][j] = vis[i-1][j]+Triangle[i][j];
    32                   else if(j==i) vis[i][j] = vis[i-1][j-1]+Triangle[i][j];
    33                   else vis[i][j] = max(vis[i-1][j]+Triangle[i][j],vis[i-1][j-1]+Triangle[i][j]);
    34              }
    35          }
    36          int ans = 0;
    37          for(i=1;i<n;++i)
    38              ans = max(ans,vis[n][i]);
    39          cout<<ans<<endl;
    40     }
    41     
    42     return 0;
    43 }

  • 相关阅读:
    checkbox 全选与全消
    sql server 关联和一些函数
    checkbox 判断是否选择
    sql 总结
    前台写逻辑
    android应用开发——popupWindow非全屏显示
    整理PostgreSQL数据库占用磁盘空间
    PHP常用的几个函数
    MySQL,PostgreSQL系统表(确认配置是否生效)
    Linux,查看目录大小
  • 原文地址:https://www.cnblogs.com/Bincoder/p/5071898.html
Copyright © 2011-2022 走看看