Algorithm

[BOJ] 11052번 : 카드 구매하기

rudgh99_algo 2024. 9. 26. 16:39

1. problem : 

https://www.acmicpc.net/problem/11052

 

2. solution 1 :

#include <bits/stdc++.h>
using namespace std;
int t; 
int a[1005]; 
int d[1005]; // i일때 최댓값 

int main(void) {
	ios::sync_with_stdio(0);
	cin.tie(0);
	cin >> t; 
	for (int i = 1; i <= t; i++) cin >> a[i]; 

	d[0] = 0;
	for (int i = 1; i <= t; i++) {
		for (int j = 1; j <= i; j++) {
			d[i] = max(d[i], d[i-j] + a[j]);
		}
	}
	int ans = 0;
	for (int i = 1; i <= t; i++) {
		ans = max(ans, d[i]);
	}
	cout << ans;
}

dp를 이용해 풀었다. 따라서 세 가지 스텝을 따른다. 

1. 테이블을 정의한다. d[i] = i개를 살 때, 최대 금액이다. 

2. 점화식을 작성한다. d[i] = max(d [i] , d [i-j] + a [j])) 

3. 초기값을 설정한다. d[0] = 0으로 초기화한다. 

나는 이 풀이를 풀 때, d[i]를 구하는 과정에서, 중복이라는 과정이 나타날 수 있는지 몰랐다. 직접 손으로 써본 경우, 가능했다. 

 

3. solution 2 :

// Authored by : tongnamuu
// Co-authored by : -
// http://boj.kr/a9eee96f33c54876b9d5ba0b1c3bb246
#include <bits/stdc++.h>
using namespace std;
int d[1001];
int main(void){
  ios::sync_with_stdio(0);
  cin.tie(0);
  int n;cin>>n;
  for(int i=1;i<=n;++i) cin>>d[i];
  for(int i=1;i<=n;++i) for(int j=1;j<i;++j) d[i] = max(d[i-j] + d[j], d[i]);
  cout << d[n];
}

source code 출처 : https://github.com/encrypted-def/basic-algo-lecture/blob/master/0x10/solutions/11052.cpp

 

basic-algo-lecture/0x10/solutions/11052.cpp at master · encrypted-def/basic-algo-lecture

바킹독의 실전 알고리즘 강의 자료. Contribute to encrypted-def/basic-algo-lecture development by creating an account on GitHub.

github.com