首页 > 代码库 > hoj_10014_二维DP
hoj_10014_二维DP
The Triangle | |
Time Limit: 1000ms, Special Time Limit:2000ms, Memory Limit:32768KB | |
Total submit users: 952, Accepted users: 860 | |
Problem 10014 : No special judgement | |
Problem description | |
| |
Input | |
Your program is to read from standard input. The first line contains one integer T, the number of test cases, for each test case: the first line contain a 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 for each test case one line. | |
Sample Input | |
1 5 7 3 8 8 1 0 2 7 4 4 4 5 2 6 5 | |
Sample Output | |
30 |
这道题是一个简单的二维DP,核心 dp[i][j] = max(dp[i-1][j-1], dp[i-1][j]) + value[i][j];
AC代码如下:
1 #include<cstdio> 2 using namespace std; 3 int main() 4 { 5 int ans; 6 int n,m; 7 int a[100][100]; 8 int b[100][100]; 9 scanf("%d",&n); 10 while(n--) 11 { 12 scanf("%d",&m); 13 for(int i=0;i<m;i++) 14 for(int j=0;j<=i;j++) 15 scanf("%d",&a[i][j]); 16 b[0][0]=a[0][0]; 17 for(int i=1;i<m;i++) 18 { 19 b[i][0]=a[i][0]+b[i-1][0]; 20 b[i][i]=a[i][i]+b[i-1][i-1]; 21 for(int j=1;j<i;j++) 22 { 23 if(b[i-1][j-1]>b[i-1][j]) 24 b[i][j]=a[i][j]+b[i-1][j-1]; 25 else 26 b[i][j]=a[i][j]+b[i-1][j]; 27 } 28 } 29 ans=b[m-1][0]; 30 for(int i=0;i<m;i++) 31 { 32 if(b[m-1][i]>ans) 33 ans=b[m-1][i]; 34 } 35 printf("%d\n",ans); 36 } 37 return 0; 38 }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。