๐Ÿ˜‰/์ฝ”๋”ฉํ…Œ์ŠคํŠธ

[์•Œ๊ณ ๋ฆฌ์ฆ˜] ์ •์ˆ˜ ์‚ผ๊ฐํ˜• (๋ฐฑ์ค€, 1932)

ruhz 2020. 11. 20. 15:34

๋ฌธ์ œ

 

1932๋ฒˆ: ์ •์ˆ˜ ์‚ผ๊ฐํ˜•

์ฒซ์งธ ์ค„์— ์‚ผ๊ฐํ˜•์˜ ํฌ๊ธฐ n(1 ≤ n ≤ 500)์ด ์ฃผ์–ด์ง€๊ณ , ๋‘˜์งธ ์ค„๋ถ€ํ„ฐ n+1๋ฒˆ์งธ ์ค„๊นŒ์ง€ ์ •์ˆ˜ ์‚ผ๊ฐํ˜•์ด ์ฃผ์–ด์ง„๋‹ค.

www.acmicpc.net

 

 

ํ’€์ด

 

ruhz3/CodingTest

To prepare for coding test. Contribute to ruhz3/CodingTest development by creating an account on GitHub.

github.com

#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;

int map[500][500];
int cache[501][501];
int N;

int findMaxWay(int row, int col) {
	int &ret = cache[row][col];
	// ๊ธฐ์ € ์‚ฌ๋ก€ : ์‚ผ๊ฐํ˜•์˜ ๋์— ๋„๋‹ฌ
	if (row == N - 1) {
		return ret = map[row][col];
	}
	// ๋ฉ”๋ชจ์ด์ œ์ด์…˜
	if (ret != -1) {
		return ret;
	}
	// ๋‘ ๊ฐˆ๋ž˜ ๊ธธ์ค‘์—์„œ ๋” ํฐ ๊ธธ์„ ์ฐพ์•„ ๋”ํ•จ
	ret = map[row][col];
	int tmp = -1;
	for (int i = col; i <= col + 1; i++) {
		tmp = max(tmp, findMaxWay(row + 1, i));
	}
	ret += tmp;
	return ret;
}

int main() {
	cin >> N;
	memset(cache, -1, sizeof(cache));
	for (int i = 0; i < N; i++) {
		for (int j = 0; j <= i; j++) {
			cin >> map[i][j];
		}
	}
	cout << findMaxWay(0, 0) << endl;

	return 0;
}

๋งค๋ฒˆ ์„ ํƒ์—์„œ ํฐ ๊ฒƒ์„ ์„ ํƒํ•˜๊ธฐ๋งŒ ํ•˜๋ฉด ๋œ๋‹ค๊ณ  ์ƒ๊ฐํ•˜๋ฉด ํฐ ์˜ค์‚ฐ์ด๋‹ค. ๋” ํฐ ๊ฐ’์„ ๊ณจ๋ž์ง€๋งŒ ๊ทธ๋กœ ์ธํ•ด ๋‹ค์Œ ์„ ํƒ์ง€๊ฐ€ ํ›จ์”ฌ ์ž‘์•„์งˆ ์ˆ˜๋„ ์žˆ๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค. ๋”ฐ๋ผ์„œ ๋ชจ๋“  ๊ฒฝ๋กœ๋ฅผ ๋น„๊ตํ•ด๋ด์•ผ ํ•จ์„ ์•Œ ์ˆ˜ ์žˆ๋‹ค. ๊ทธ๋ ‡๋‹ค๋ฉด ์™„์ „ ํƒ์ƒ‰์„ ๋จผ์ € ์ƒ๊ฐํ•ด ๋ณผ ์ˆ˜ ์žˆ๋‹ค. ํ•˜์ง€๋งŒ ํ‰์†Œํ•˜๋˜ ์™„์ „ํƒ์ƒ‰์€ ์ด ๊ฒฝ์šฐ ๋ถˆํ•„์š”ํ•œ ํ•จ์ˆ˜ํ˜ธ์ถœ์ด ๋งŽ์•„ ๋น„ํšจ์œจ์ ์ด๋‹ค.

ํƒ์ƒ‰ ๋„์ค‘, ํ‘œ์‹œํ•œ 8์—์„œ 7์„ ๊ณจ๋ผ ์•„๋žซ์ธต์œผ๋กœ ๋‚ด๋ ค๊ฐ„๋‹ค๊ณ  ๊ฐ€์ •ํ•˜์ž. 7์—์„œ ๋‚ด๋ ค๊ฐˆ ์ˆ˜ ์žˆ๋Š” ์ตœ๋Œ€์˜ ๊ฒฝ๋กœ๋Š” 5์ด๋‹ค. ํ‘œ์‹œํ•œ 1์—์„œ 7์„ ๊ณจ๋ผ ๋‚ด๋ ค๊ฐ„๋‹ค๊ณ  ํ•˜๋”๋ผ๋„ 7์—์„œ ๋‚ด๋ ค๊ฐˆ ์ˆ˜ ์žˆ๋Š” ์ตœ๋Œ€๊ฒฝ๋กœ๋Š” ์ •ํ•ด์ ธ์žˆ๋‹ค. ๊ทธ๋ ‡๋‹ค๋ฉด ๊ตณ์ด 7์—์„œ ํ•จ์ˆ˜๋ฅผ ํ˜ธ์ถœํ•  ํ•„์š” ์—†์ด 8์—์„œ ํ˜ธ์ถœํ–ˆ๋˜ ๊ฐ’์„ ์‚ฌ์šฉํ•˜๋ฉด ํ˜ธ์ถœ ํšŸ์ˆ˜๋ฅผ ํš๊ธฐ์ ์œผ๋กœ ์ค„์ผ ์ˆ˜ ์žˆ์„ ๊ฒƒ์ด๋‹ค.

์ด๋Ÿฐ ๋ฐฉ๋ฒ•์„ ๋™์ ๊ณ„ํš๋ฒ•์ด๋ผ๊ณ  ํ•œ๋‹ค.

"cache[๋ช‡๋ฒˆ์งธ ํ–‰][๋ช‡๋ฒˆ์งธ ์—ด] = ์—ฌ๊ธฐ์„œ ๋ฐ‘์œผ๋กœ ๋‚ด๋ ค๊ฐˆ ์ˆ˜ ์žˆ๋Š” ์ตœ๋Œ€ ๊ฒฝ๋กœ์˜ ํ•ฉ"์„ ์ €์žฅํ•˜์—ฌ ํ•ด๋‹น ํ–‰์—ด์— ๋„์ฐฉํ–ˆ์„ ๊ฒฝ์šฐ, ๋ฐ”๋กœ ๊ฐ’์„ ๋ฐ˜ํ™˜ํ•œ๋‹ค๋ฉด, ํ‘œ์‹œํ•œ 1์—์„œ 7๋กœ ๋‚ด๋ ค๊ฐ”์„ ๋•Œ, 4ํ–‰ 2์—ด์ด๋ฏ€๋กœ, cache[3][1]์„ ์ฆ‰์‹œ ๋ฐ˜ํ™˜ํ•œ๋‹ค.