티스토리 뷰
문제 링크 : https://www.acmicpc.net/problem/2342
🍊해결방법
- 왼발, 오른발 방향의 값에 따라 결과값이 달라짐
- 왼발로 이동하는 경우의 수와 오른발로 이동하는 경우의 수 확인
- dirCal() 함수를 통해 방향에 이동에 대한 값 계산
- 왼발이동하는 값(tmp1) 과 오른발이동하는 값(tmp2) 최솟값 return
- 중복되는 경우 있으므로 dp 활용해서 저장
😀풀이
import java.util.*;
import java.io.*;
public class Main {
static int N;
static int[] arr;
static int[][][] dp;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// 왼발 오른발에 방향 저장
// 문제의 조건에 맞게 방향 이동할때 힘 적용
// 마지막까지 했을 때 최솟값 갱신
// 중복되는 상황이 있을 수 있으므로 dp 사용
StringTokenizer st = new StringTokenizer(br.readLine());
N = st.countTokens()-1;
arr = new int[N];
for(int i=0; i<N; i++){
arr[i] = Integer.parseInt(st.nextToken());
}
dp = new int[N][5][5];
for(int i=0; i<N; i++){
for(int j=0; j<5; j++){
Arrays.fill(dp[i][j], -1);
}
}
int ans = go(0,0,0);
System.out.println(ans);
}
static int go(int idx, int left, int right){
if (idx == N){
return 0;
}
if (dp[idx][left][right] != -1) return dp[idx][left][right];
int power = dirCal(arr[idx], left);
int tmp1 = go(idx+1, arr[idx], right) + power;
power = dirCal(arr[idx], right);
int tmp2 = go(idx+1, left, arr[idx]) + power;
int tmp = Math.min(tmp1, tmp2);
dp[idx][left][right] = tmp;
return dp[idx][left][right];
}
static int dirCal(int next, int now){
if (now == 0) return 2;
if (now == next) return 1;
if (now == 1 && next == 3 || now == 3 && next == 1) return 4;
if (now == 2 && next == 4 || now == 4 && next == 2) return 4;
return 3;
}
}
'알고리즘 > 백준' 카테고리의 다른 글
[백준] 1256 사전 - DP, 조합 (0) | 2024.09.21 |
---|---|
[백준] 13397 구간 나누기2 - 이진탐색 (0) | 2024.09.20 |
[백준] 12015 가장 긴 증가하는 부분 수열2 - 이진탐색 (0) | 2024.09.13 |
[백준] 17779 게리맨더링2 - 구현 (0) | 2024.09.01 |
[백준] 20057 마법사 상어와 토네이도 - 구현 (0) | 2024.08.30 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 스프링부트3 java 버전오류
- 백준 경사로 자바
- 스프링부트3
- 스프링부트3 자바 17 오류
- #스프링부트 자바버전 오류
- BFS
- leetcode 1552
- 1482
- 탑다운dp
- sql
- 백준 14890 자바
- 슬라이딩윈도우
- 구현
- 스프링부트3 자바 버전
- 백준 경사로
- dfs
- 백준
- 조합
- 투포인터
- 유니온파인드
- 티스토리챌린지
- 누적합
- 탑다운
- 백준 14890 경사로
- 오블완
- 이진탐색
- dp
- 위상정렬
- 바텀업
- 백준 14890
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 | 31 |
글 보관함