[ 백준 ] 2309 - 백설공주와 난쟁이 (with. JAVA)


💡문제 분석 요약
-- 문제 --
입력 : 아홉 개의 줄에 걸쳐 난쟁이들의 키가 주어진다. 주어지는 키는 100을 넘지 않는 자연수이며, 아홉 난쟁이의 키는 모두 다르며, 가능한 정답이 여러 가지인 경우에는 아무거나 출력한다.
출력 : 일곱 난쟁이의 키를 오름차순으로 출력한다. 일곱 난쟁이를 찾을 수 없는 경우는 없다.
💡알고리즘 설계
Scanner로 입력받기
List로 값 입력.
sum을 미리 구해주고 랜덤으로 2개 고른 후 빼준 값이 100인지 확인
확인된 2개의 값ㅇ르 null로 변환해주고 size -2 해준 후 나머지 출력
💡코드
package backjoon;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class BackJoon2309 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
List<Integer> lists=new ArrayList<>();
for (int i = 0; i < 9; i++) {
int num = Integer.parseInt(br.readLine());
if (num > 100 && lists.contains(num)) {
break;
}
lists.add(i,num);
}
lists.sort(null);
int sum=0;
for (Integer list : lists) {
sum += list;
}
for (int i = 0; i < lists.size()-1; i++) {
for (int j = 1; j < lists.size(); j++) {
sum = sum - (lists.get(i)+lists.get(j));
if (sum == 100) {
lists.get(i)=null;
lists.get(j)=null;
lists.size() =-2;
}
}
}
}
}
💡시간복잡도
O(N*N)
💡틀린 이유
크기가 정해져 있다 !! → 배열 이용
BufferReader 보다 Scanner 사용 먼저 떠오름
9개 중 랜덤으로 7개 골라서 합이 100 되는 알고리즘 생각함
💡틀린 부분 수정 or 다른 풀이
package Practice;
import java.io.*;
import java.util.Arrays;
public class BackJoon_2309 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
int[] lists = new int[9];
int sum = 0;
int spy1=0, spy2=0;
for (int i = 0; i < 9; i++) {
lists[i] = Integer.parseInt(br.readLine());
sum += lists[i];
}
Arrays.sort(lists);
for (int i = 0; i < 8; i++) {
for (int j = i+1; j < 9; j++) {
if (sum - lists[i] - lists[j] == 100) {
spy1=i;
spy2=j;
break;
}
}
}
for (int i = 0; i < lists.length; i++) {
if (i == spy1 || i == spy2) {
continue;
}
System.out.println(lists[i]);
}
bw.flush();
bw.close();
}
}
💡느낀점 or 기억 할 정보
BufferedReader br = new BufferedReader(new InputStreamReader(System.in))
입력할 때 한 문자씩 버퍼로 이동 → 가득차거나 개행문자 발견 → 버퍼내용을 한번에 프로그램으로 전달
형변환 무조건 해주기 !현재는 System.out.println을 사용했지만 데이터 양이 많아지면 BufferedWriter 사용
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out))
bw.write(입력문자) / bw.flush() : 남아있는 데이터 모두 출력 / bw.newLine() / bw.close()
버퍼를 잡았기 때문에 반드시 close해주기
Subscribe to my newsletter
Read articles from Soyulia directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Soyulia
Soyulia
Nice to meet u :) Im Backend Developer