[ACM POJ 1163] 동적 계획 시작 연습(一)The Triangle

2110 단어 동적 기획
The Triangle
Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 28092 Accepted: 16504
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
Source POJ1163
이 문제가 매거법(폭력사상)으로 수탑의 층수가 조금 큰 경우(예를 들어 31) 열거해야 할 경로조수는 매우 방대한 수(2^30=1024^3>10^9=10억)가 될 것이다.
따라서 우리는 아래에서 위로 밀어낼 수 있다. 인접한 두 수 중에서 비교적 큰 것을 찾아 상층과 덧붙인다. 얻은 결과는 인접한 두 수 중에서 비교적 큰 것을 찾아 상층과 덧붙인다.
코드는 다음과 같습니다.
#include<stdio.h>
int main(){
	int n, i, j;
	scanf("%d", &n);
	int **a = new int*[n];
	for(i = 0; i < n; ++i){
		a[i] = new int[i + 1];
		for(j = 0; j <= i; ++j){
			scanf("%d", &a[i][j]);
		}
	}
	for(i = n - 2; i >=0; --i){
		for(j = 0; j <= i; ++j){
			a[i][j] += a[i + 1][j] > a[i + 1][j + 1] ? a[i + 1][j] : a[i + 1][j + 1];
		}
	}
	printf("%d", a[0][0]);
	return 0;
}

===================서명서류========================원문 주소(내 블로그):http://www.clanfei.com/2012/04/433.html방문과 교류를 환영합니다. 제가 왜 블로그를 하나 더 만들어야 하는지에 대해 저는 앞부분을 사랑하고 홈페이지를 사랑하기 때문에 더욱 자유롭고 진정으로 저만의 작은 사이트를 원합니다. 그렇게 유명하지는 않겠지만 적어도 저를 위해 배로 노력하게 할 수 있습니다. =======================================서명 서류====================

좋은 웹페이지 즐겨찾기