๐Ÿ’œ๊ฐœ๋ฐœ๊ณผ ์ผ์ƒ (โ‰ง∇โ‰ฆ)๏พ‰

[๋ฐฑ์ค€ c++] 2579 ๊ณ„๋‹จ ์˜ค๋ฅด๊ธฐ (์‹ค3) ๋ณธ๋ฌธ

CS/๋ฐฑ์ค€

[๋ฐฑ์ค€ c++] 2579 ๊ณ„๋‹จ ์˜ค๋ฅด๊ธฐ (์‹ค3)

๊ฐ•์˜์„œ 2022. 2. 10. 00:36

๐Ÿ“Œ ์„œ๋ก 

์ด ๋ฌธ์ œ๋Š” ๋‚ด๊ฐ€ ์•Œ๊ณ ๋ฆฌ์ฆ˜ ์Šคํ„ฐ๋””๋ฅผ ์—ด์‹ฌํžˆ ํ–ˆ์„ ๋•Œ ํ’€์—ˆ๋˜ ๋ฌธ์ œ๋‹ค

๊ฐ„๋‹จํ•˜๋ฉด์„œ๋„ ๋™์ ํ• ๋‹น์˜ ๊ฐœ๋…์„ ์ž˜ ์–ป์„ ์ˆ˜ ์žˆ๋Š” ์ข‹์€ ๋ฌธ์ œ!

 

์ด ๋ฌธ์ œ๋Š” ์‚ฌ์‹ค ๋™์  ๊ณ„ํš ์ด์™ธ์— ์žฌ๊ท€ ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•ด์„œ ํ’€ ์ˆ˜๋„ ์žˆ์ง€๋งŒ ๊ทธ๋ ‡๊ฒŒ ํ‘ผ๋‹ค๋ฉด

์‹œ๊ฐ„ ์ดˆ๊ณผ ๋ฌธ์ œ๋กœ ๋งž์„ ์ˆ˜ ์—†์—ˆ๋‹ค.

 

๐Ÿ™…๐Ÿป‍โ™‚๏ธ ํ‹€๋ฆฐ ๋‹ต์•ˆ

#include <iostream>
using namespace std;

int N;
int MAX;
int* stair;
int result;

void function(int idx, int nextCnt) {
	
	if (idx == N - 1 ) {
		if (nextCnt == 2) return;
		if (MAX < result + stair[idx]) MAX = result + stair[idx] ;
	}
	else if(nextCnt != 2){
		result += stair[idx];
		if (nextCnt != 2) 	//1์นธ์œ„๋กœ ์˜ฌ๋ผ๊ฐ€๊ณ  ์‹ถ์€๋ฐ ๋จผ์ € ํ™•์ธ
			function(idx + 1, nextCnt + 1);
		if (idx + 2 < N) 
			function(idx + 2, 0);
		result -= stair[idx];
	}

}

int main() {

	cin >> N; if (N < 1 || N > 300) return 0 ;
	stair = new int[N];
	for (int i = 0; i < N; i++) cin >> stair[i];
	MAX = 0; result = 0;

	function(0,0);
	function(1,0);

	cout << MAX << endl;

	return 0;
}

์žฌ๊ท€๋ฅผ ์‚ฌ์šฉํ•œ ์ฝ”๋“œ์ด๋‹ค.

๋ชจ๋“  ๊ฐ€๋Šฅ์„ฑ์„ ๋‹ค ํƒ์ƒ‰ํ•œ ํ›„ ๊ฐ€์žฅ ์ตœ๋Œ€๊ฐ’์ด ๋‚˜์˜ค๋Š” ๊ฒฝ์šฐ๋ฅผ ์ฐพ๋Š” ๋ฐฉ๋ฒ•์ธ๋ฐ ์ด๋ ‡๊ฒŒ ํ•˜๋ฉด ์•„๋ž˜์™€ ๊ฐ™์ด ์‹œ๊ฐ„์ดˆ๊ณผ ๊ฒฐ๊ณผ๋กœ

๋ฌธ์ œ๋ฅผ ํ’€ ์ˆ˜ ์—†๋‹ค.

 

 

๋™์  ๊ณ„ํš๋ฒ• ( ๋‹ค์ด๋‚˜๋ฏน ํ”„๋กœ๊ทธ๋ž˜๋ฐ ) ์— ๋Œ€ํ•ด์„œ ์•Œ์•„์•ผ ๋ฌธ์ œ์˜ ํ•ด๋‹ต์„ ์ฐพ์„ ์ˆ˜ ์žˆ๋‹ค.

โœจ๋™์ ๊ณ„ํš๋ฒ• ๊ด€๋ จ ๊ธ€ ์ฐธ๊ณ  https://greedy-blow-you-away12.tistory.com/8

 

๐Ÿ’ป ์ •๋‹ต ์ฝ”๋“œ

#include <cstdio>
using namespace std;
int max(int a, int b) { return a > b ? a : b; }
int main () {
    int n, i;
    int arr[300];
    int dp[300];
    scanf("%d", &n); for (i = 0; i < n; i++) scanf("%d", &arr[i]);
    dp[0] = arr[0];
    dp[1] = max(arr[0]+arr[1], arr[1]);
    dp[2] = max(arr[0]+arr[2], arr[1]+arr[2]);
    for (i = 3; i < n; i++) dp[i] = max(dp[i-2] + arr[i], dp[i-3] + arr[i-1] + arr[i]);
    printf("%d\n", dp[n-1]);
    return 0;
}

 

 

โฑ ๊ฒฐ๊ณผ