12865번 : 평범한 배낭
문제는 다음과 같습니다.
https://www.acmicpc.net/problem/12865
12865번: 평범한 배낭
첫 줄에 물품의 수 N(1 ≤ N ≤ 100)과 준서가 버틸 수 있는 무게 K(1 ≤ K ≤ 100,000)가 주어진다. 두 번째 줄부터 N개의 줄에 거쳐 각 물건의 무게 W(1 ≤ W ≤ 100,000)와 해당 물건의 가치 V(0 ≤ V ≤ 1,000)
www.acmicpc.net
풀이 코드는 다음과 같습니다.
#include<iostream>
#include<algorithm>
using namespace std;
int N, K;
int DP[101][100001];
int W[101];
int V[101];
int main()
{
cin >> N >> K;
for (int i{1}; i <= N; i++)
{
cin >> W[i] >> V[i];
}
for (int i{1}; i <= N; i++)
{
for (int j = 1; j <= K; j++)
{
if (j - W[i] >= 0)
{
DP[i][j] = max(DP[i - 1][j], DP[i - 1][j - W[i]] + V[i]);
}
else
{
DP[i][j] = DP[i - 1][j];
}
}
}
cout << DP[N][K];
}
처음에 굉장히 헤맨 문제인데 이런 문제를 "배낭 문제"라 하여 다루고 있음을 알게 되었습니다.
https://en.wikipedia.org/wiki/Knapsack_problem
Knapsack problem - Wikipedia
From Wikipedia, the free encyclopedia Jump to navigation Jump to search Problem in combinatorial optimization Example of a one-dimensional (constraint) knapsack problem: which boxes should be chosen to maximize the amount of money while still keeping the o
en.wikipedia.org
배낭 문제는 크게 "분할 가능 배낭 문제", "0-1 배낭 문제"로 나누어지며 이번 문제는 0-1 배낭 문제를 그대로 쓰면 되는 문제입니다.
이 문제를 푸는 방법에 어려움을 느끼셨으면 배낭문제에 대해 찾아보시는 것을 추천드립니다.