https://www.acmicpc.net/problem/7490
7490번: 0 만들기
각 테스트 케이스에 대해 ASCII 순서에 따라 결과가 0이 되는 모든 수식을 출력한다. 각 테스트 케이스의 결과는 한 줄을 띄워 구분한다.
www.acmicpc.net
코드설명
완전탐색, 문자열 ( stringtokenizer ) 을 활용하는 문제입니다.
문제에서 기억해야할점들
- StringTokenizer 사용을 통하여 계산식의 값들을 "+", "-" 로 나눕니다. StringTokenizer를 활용하여 손쉽게 문자열을 나눌 수 있습니다.
//1+2+3+4+56+7 //"1", "+", "2", "+" ... 이렇게 tokenizer true값을 설정하여 delim 값도 포함시킵니다. StringTokenizer numberAndOperation = new StringTokenizer(calculateOperation, "+|-",true); while(numberAndOperation.hasMoreTokens()) { String a = numberAndOperation.nextToken(); if( a.equals("+")) { int b = Integer.parseInt(numberAndOperation.nextToken()); //처음 숫자는 더하고시작 sum += b; }else if( a.equals("-")) { int b = Integer.parseInt(numberAndOperation.nextToken()); //처음 숫자는 더하고시작 sum -= b; } }
코드
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class Main { public static int T, N; public static int[] arr; public static int answer = Integer.MAX_VALUE; public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); T = Integer.parseInt(st.nextToken()); for(int t=0;t<T;t++) { st = new StringTokenizer(br.readLine()); N = Integer.parseInt(st.nextToken()); simulate(2, 1, new StringBuilder("1")); System.out.println(); } } public static void simulate(int idx, int cnt, StringBuilder sb) { if(cnt == N ) { String calculateOperation = sb.toString().replaceAll(" ", ""); //1+2+3+4+56+7 //"1", "+", "2", "+" ... 이렇게 tokenizer true값을 설정하여 delim 값도 포함시킵니다. StringTokenizer numberAndOperation = new StringTokenizer(calculateOperation, "+|-",true); int sum = Integer.parseInt(numberAndOperation.nextToken()); //처음 숫자는 더하고시작 while(numberAndOperation.hasMoreTokens()) { String a = numberAndOperation.nextToken(); if( a.equals("+")) { int b = Integer.parseInt(numberAndOperation.nextToken()); //처음 숫자는 더하고시작 sum += b; }else if( a.equals("-")) { int b = Integer.parseInt(numberAndOperation.nextToken()); //처음 숫자는 더하고시작 sum -= b; } } if( sum == 0) { System.out.println(sb.toString()); } return ; } for(int i=idx;i<=N;i++) { // 공백일시 (아스키코드 순서에 따라) simulate(i+1, cnt + 1, new StringBuilder(sb).append(" ").append(i)); // "+" 일시 simulate(i+1, cnt + 1, new StringBuilder(sb).append("+").append(i)); // "-" 일시 simulate(i+1, cnt + 1, new StringBuilder(sb).append("-").append(i)); } } }
'알고리즘 > 백준' 카테고리의 다른 글
[백준] 9935 문자열 폭발 - StringBuilder + 아이디어 JAVA (0) | 2023.08.12 |
---|---|
[백준] 1987 알파벳 - Backtracking(백트래킹) + DFS(깊이우선탐색) + HashSet(해시셋) JAVA (0) | 2023.08.12 |
[백준] 2138 전구와 스위치 - 그리디 + 아이디어 JAVA (0) | 2023.08.11 |
[백준] 14719 빗물 - 구현 + 시뮬레이션 JAVA (0) | 2023.08.10 |
[백준] 2493 탑 - 자료구조 Stack(스택) JAVA (0) | 2023.08.10 |