Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
Tags
- 16202
- 22869
- 진법변환 #2to10 #10to2 #이진법 #십진법 #변환 #bitset #c++
- 백준 #다익스트라 #dijkstra #9370 #c++
- 30870
- LIS #가장긴증가하는부분수열 #
- 3D #Reconstruction #computer #vision #volume #metric #tsdf #kinect #fusion
- 줄어드는수
- 3343
- graph #최단경로
- 코딩
- hcpc
- 투포인터 #백준 #boj #20922 #22862
- 이분탐색 #dp #11053
- N번째큰수
- 사이클 없는 그래프
- 쌤쌤쌤
- c++ #boj #
- 1174
- C++
- graph
- boj #백준
- 20117
- 백준
- 호반우 상인
- BOJ
- backtracking #codetree #디버깅 #삼성코테
- 최소 #공배수 #최대 #공약수 #유클리드 #호제법 #lcm #gcd #c++ #boj #3343 #백준 #장미
- c++ #입출력 #속도 #ios #sync_with_stdio #cin #cout #tie
- 레드아보
Archives
- Today
- Total
hyunjin
[BOJ22869 징검다리 건너기(small)] 다이나믹 프로그래밍 dp 본문
728x90
1. Top Down, 재귀
N에 도달 가능 여부만 판단한다.
#include <iostream>
#include <cstring>
#include <cmath>
#define MAX_N 5001
using namespace std;
int N, K;
int e[MAX_N], dp[MAX_N];
// top - down
// 도달 가능 여부만 확인하면 된다
// 갈 수 있으면 바로 끝
// 2중 for 사용 가능
int canGo(int target) {
int& ret = dp[target];
if (ret != -1) return ret;
ret = 0; //0으로 설정, 일단 못간다 세팅
// i -> target으로 이동
for (int i = 0; i < target; i++) {
int power = (target - i) * (1 + abs(e[target] - e[i]));
if (power <= K) {
if (canGo(i)) {
return ret = 1; // 1
}
}
}
return ret; // 0
}
int main() {
ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
cin >> N >> K;
for (int i = 0; i < N; i++) cin >> e[i];
memset(dp, -1, sizeof(dp)); //-1 : 아직 안봤다.
dp[0] = 1; // 갈 수 있다.
cout << (canGo(N-1) ? "YES" : "NO");
return 0;
}

2. Bottom Up , 2 중 for
#include <iostream>
#include <cstring>
#include <cmath>
#define MAX_N 5001
#define INF 0x7f7f7f7f
using namespace std;
int N, K;
int e[MAX_N];
int dp[MAX_N];
int main() {
ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
cin >> N >> K;
for (int i = 1; i <= N; i++) cin >> e[i];
memset(dp, INF, sizeof(dp));
dp[0] = dp[1] = 0;
for (int i = 1; i <= N - 1; i++) {
for (int j = i + 1; j <= N; j++) {
int power = (j - i) * (1 + abs(e[j] - e[i]));
if (power > K || dp[i] == INF) continue;
dp[j] = min(power, dp[j]);
}
}
cout << ((dp[N] == INF) ? "NO" : "YES");
return 0;
}

목표 지점에 도달 가능 여부만 판단하면 되기 때문에 1번 코드가 더 효율적이다.
728x90
'알고리즘 연습 > 백준' 카테고리의 다른 글
[BOJ 20440] imso, 누적 합, 좌표 압축 (0) | 2024.06.30 |
---|---|
[BOJ 30870 사이클 없는 그래프 c++ 풀이] (1) | 2024.06.20 |
[BOJ 5875 오타 c++] 자료구조 누적 합 (0) | 2024.04.28 |
[BOJ 3343 장미] 정수론, LCM (0) | 2024.04.25 |
[BOJ 2933 미네랄] 구현 그래프 너비 깊이 우선 (0) | 2024.04.23 |