-
[dp, knapsack] 2가지 다른 풀이아무거나적어~ 2023. 8. 28. 14:42
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
dp[i] := i가치를 얻을 수 있는 최소 무게 O(N²V)
123456789101112131415161718192021222324252627282930313233343536#include <bits/stdc++.h>#define endl '\n' // don't use when you cover interactive problem#define INF 100000000 // 100,000 x 100 보다 큰거#define MAX 100000 // 1000 x 100using namespace std;typedef pair<int, int> pi;int sol(vector<int>& dp, int K){for(int v = MAX; v >= 0; v--){if(dp[v] <= K) return v;}}int main() {ios::sync_with_stdio(false);cin.tie(0), cout.tie(0);int N, K; cin >> N >> K;vector<pi> vec(N); // {weight, val}for(auto& [weight, val]: vec) cin >> weight >> val;vector<int> dp(MAX+1, INF); // i가치를 얻을 수 있는 최소 무게dp[0] = 0;for(int i = 0; i < N; i++){auto [weight, val] = vec[i];for(int v = MAX; v >= val; v--){dp[v] = min(dp[v], dp[v-val]+weight);}}cout << sol(dp, K) << endl;return 0;}csdp[i] := i무게로 얻을 수 있는 최대 가치 O(NK)
1234567891011121314151617181920212223242526#include <bits/stdc++.h>#define endl '\n' // don't use when you cover interactive problemusing namespace std;typedef pair<int, int> pi;int main() {ios::sync_with_stdio(false);cin.tie(0), cout.tie(0);int N, K; cin >> N >> K;vector<pi> vec(N); // {weight, value}for(auto&[weight, val]: vec) cin >> weight >> val;vector<int> dp(K+1, 0);for(int i = 0; i < N; i++){auto& [weight, val] = vec[i];for(int w = K; w >= weight; w--){ // 갱신순서 큰거에서 작은 순으로 해야 됨dp[w] = max(dp[w], dp[w-weight]+val);}}cout << dp[K] << endl;return 0;}cs'아무거나적어~' 카테고리의 다른 글
python3 vs pypy3 string in operator 차이 (0) 2023.09.02 python string in operator ~ O(N) (0) 2023.09.02 The Irwin-Hall distribution(Probability distribution of a sum of uniform random variables) (0) 2023.07.31 [python, jupyter] 임의의 함수의 documentation 보는 법 -> ?를 뒤에 붙이고 실행 (0) 2023.07.31 [deeplearning] sigmoid의 종류 (0) 2023.07.31