728x90
반응형
https://www.acmicpc.net/problem/1535
1. Logic
경우의 수를 나눠보게 되면 인사를 할때와 안할 때 두가지의 경우의 수로 분류할 수 있다. 각 인사를 할지 말지에 대한 고민을 풀이해야 하기 때문에 배낭 문제(KnapSack Problem)라고 볼 수 있다.
2. Code
C++
#include<bits/stdc++.h>
using namespace std;
int n;
int dp[21][101];
int lose[20];
int delight[20];
int solve(int idx, int health) {
if(idx == n) return 0;
int &ret = dp[idx][health];
if(ret != -1) return ret;
if(health+lose[idx] < 100) {
ret = max(ret, solve(idx+1, health+lose[idx])+delight[idx]);
}
ret = max(ret, solve(idx+1, health));
return ret;
}
int main() {
ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
memset(dp, -1, sizeof(dp));
cin >> n;
for(int i = 0; i < n; i++) {
cin >> lose[i];
}
for(int i = 0; i < n; i++) {
cin >> delight[i];
}
cout << solve(0, 0);
}
Python
import copy
n = int(input())
dp = [[-1] * 101 for _ in range(21)]
lose = [*map(int, input().split())]
delight = list(map(int,input().split()))
def solve(idx, health):
if(idx == n):
return 0
#ret = dp[idx][health]
if dp[idx][health] != -1:
return dp[idx][health]
if health+lose[idx] < 100:
dp[idx][health] = max(dp[idx][health], solve(idx+1, health+lose[idx])+delight[idx])
dp[idx][health] = max(dp[idx][health], solve(idx+1, health))
return dp[idx][health]
print(solve(0, 0))
알고리즘 Solve 후 제가 생각한 Logic을 기록하는 개인 공부 블로그입니다.
내용 중 최적화가 가능한 부분등은 언제든지 댓글로 틀린 부분 및 피드백 주시면 공부 및 반영하겠습니다🧐
728x90
반응형
'Algorithm > Beakjoon' 카테고리의 다른 글
[백준/Baekjoon] 2346 풍선 터뜨리기 C++/Python :: Date Structure (0) | 2024.03.14 |
---|---|
[백준/Baekjoon]1940 주몽 C++/Python :: Two pointer (0) | 2024.03.11 |
[백준/Baekjoon] 11060 점프 점프 C++/Python :: BFS (0) | 2024.02.29 |
[백준/Baekjoon] 1270 전쟁-땅따먹기 C++/Python :: Implementation (1) | 2024.02.28 |
[백준/Baekjoon] 2161 카드1 C++ :: Queue (0) | 2024.02.21 |