알고리즘

백준 5557번 1학년 (JAVA)

박카스마시며코딩 2022. 8. 4. 23:05

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

 

5557번: 1학년

상근이가 1학년 때, 덧셈, 뺄셈을 매우 좋아했다. 상근이는 숫자가 줄 지어있는 것을 보기만 하면, 마지막 두 숫자 사이에 '='을 넣고, 나머지 숫자 사이에는 '+' 또는 '-'를 넣어 등식을 만들며 놀

www.acmicpc.net

 

저는 DP를 통해 문제를 해결하였습니다.

저는 DP[인덱스][현재까지의 합] = 이때까지의 가짓수 로 저장하였습니다.

결과가 2^(63)-1 이기 때문에 long 타입으로 저장하였습니다.

 

package BOJ.dp;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.util.function.Function;

public class BOJ_5557 {

    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());
        Function<String,Integer> stoi = Integer::parseInt;
        int n = stoi.apply(st.nextToken());
        int[] input = new int[n];
        st = new StringTokenizer(br.readLine());
        for(int i = 0 ; i < n ; i++){
            input[i] = stoi.apply(st.nextToken());
        }
        long[][] dp = new long[n][LIMIT+1];
        for(int i = 0 ; i < n ; i++){
            Arrays.fill(dp[i],NOT_VALID);
        }
        long result = dfs(1,input[0],input,n,dp);
        System.out.println(result);
    }

    private static final long NOT_VALID = -1;
    private static final int LIMIT = 20;
    private static long dfs(int depth, int sum, int[] input, int n, long[][] dp) {
        if(depth == n-1){
            if(sum == input[n-1]){
                return 1;
            }else{
                return 0;
            }
        }
        if(dp[depth][sum] != NOT_VALID){
            return dp[depth][sum];
        }
        long result = 0;
        if(sum + input[depth] >= 0 && sum + input[depth] <= LIMIT){
            result += dfs(depth+1,sum + input[depth],input,n,dp);
        }
        if(sum - input[depth] >= 0 && sum - input[depth] <= LIMIT){
            result += dfs(depth+1,sum - input[depth],input,n,dp);
        }
        dp[depth][sum] = result;
        return result;
    }
}

'알고리즘' 카테고리의 다른 글

백준 1713번 후보 추천하기 (JAVA)  (0) 2022.08.06
백준 13335번 트럭 (JAVA)  (0) 2022.08.05
배준 19621번 회의실 배정2 (JAVA)  (0) 2022.08.03
백준 5430번 AC (JAVA)  (0) 2022.08.02
백준 13334번 철로 (JAVA)  (0) 2022.08.01