알고리즘

백준 7490번 0 만들기 (JAVA)

박카스마시며코딩 2023. 10. 29. 20:44

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

 

7490번: 0 만들기

각 테스트 케이스에 대해 ASCII 순서에 따라 결과가 0이 되는 모든 수식을 출력한다. 각 테스트 케이스의 결과는 한 줄을 띄워 구분한다.

www.acmicpc.net

 

저는 구현을 통해 문제를 해결하였습니다.

저는 만들 수 있는 모든 수식(문자열)을 만들고 해당 수식이 0이 되는지를 판단하였습니다. 

이때 저는 뒤에서부터 계산을 하였습니다. 뒤에서부터 숫자 빈칸이라면 계속 숫자들을 만들어나가고, + 또는 - 가 나온다면 그 값을 결과값에 더하거나 뺴서 문제를 해결하였습니다.

앞에서 부터하면 이 값을 빼야하는지 더해야하는지를 판단하기 어렵기 때문에 뒤에서부터 하여 문제를 해결하였습니다.

 

package BOJ.etc;

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

public class BOJ_7490 {

    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        Function<String,Integer> stoi = Integer::parseInt;
        int n = stoi.apply(br.readLine());
        for(int i = 0 ; i < n ; i++){
            int num = stoi.apply(br.readLine());
            cal(2,"1",num);
            resultString.append('\n');
        }
        System.out.println(resultString);
    }
    private static StringBuilder resultString = new StringBuilder();
    private static void cal(int depth, String s, int num) {
        if(depth > num){
            if(isZero(s)){
                resultString.append(s);
                resultString.append('\n');
            }
            return ;
        }
        cal(depth+1,s+" "+depth,num);
        cal(depth+1,s+"+"+depth,num);
        cal(depth+1,s+"-"+depth,num);
    }

    private static boolean isZero(String s) {
        int result = 0;
        int num = 0;
        int temp = 1;
        for(int i = s.length()-1 ; i >= 0 ; i--){
            char ch = s.charAt(i);
            if(isNumber(ch)){
                num += (ch - '0') * temp;
            }
            if( i == 0){
                result += num;
            }
            if(ch == ' '){
                temp *= 10;
            }
            if(ch == '+'){
                temp = 1;
                result += num;
                num = 0;
            }
            if(ch == '-'){
                temp = 1;
                result -= num;
                num = 0;
            }
        }
        if(result == 0){
            return true;
        }
        return false;
    }

    private static boolean isNumber(char ch) {
        if(ch >= '0' && ch <= '9'){
            return true;
        }
        return false;
    }
}