Algorithm Test/백준

[백준] 1062. 가르침 (JAVA)

김맷돌 2021. 5. 11. 13:45
반응형

👨‍🏫 가르침

 

백트래킹을 이용해 해결할 수 있다. 

 


문제

남극에 사는 김지민 선생님은 학생들이 되도록이면 많은 단어를 읽을 수 있도록 하려고 한다. 그러나 지구온난화로 인해 얼음이 녹아서 곧 학교가 무너지기 때문에, 김지민은 K개의 글자를 가르칠 시간 밖에 없다. 김지민이 가르치고 난 후에는, 학생들은 그 K개의 글자로만 이루어진 단어만을 읽을 수 있다. 김지민은 어떤 K개의 글자를 가르쳐야 학생들이 읽을 수 있는 단어의 개수가 최대가 되는지 고민에 빠졌다.

 

남극언어의 모든 단어는 "anta"로 시작되고, "tica"로 끝난다. 남극언어에 단어는 N개 밖에 없다고 가정한다. 학생들이 읽을 수 있는 단어의 최댓값을 구하는 프로그램을 작성하시오.

 

입력

첫째 줄에 단어의 개수 N과 K가 주어진다. N은 50보다 작거나 같은 자연수이고, K는 26보다 작거나 같은 자연수 또는 0이다. 둘째 줄부터 N개의 줄에 남극 언어의 단어가 주어진다. 단어는 영어 소문자로만 이루어져 있고, 길이가 8보다 크거나 같고, 15보다 작거나 같다. 모든 단어는 중복되지 않는다.

 

출력

첫째 줄에 김지민이 K개의 글자를 가르칠 때, 학생들이 읽을 수 있는 단어 개수의 최댓값을 출력한다.

 


🔑  IDEA

  1. 주어진 단어들 중 a,n,t,i,c을 제외한 알파벳을 모두 찾아 unknown에 저장한다.
  2. unknown에 저장된 알파벳들을 바탕으로 백트래킹을 이용해 글자를 가르칠 수 있는 경우를 모두 탐색해 각 경우에 대한 학생들이 읽을 수 있는 단어 개수의 최댓값을 구한다. 
  3. 단, K보다 unknown.size()가 작을 수 있음에 주의한다.

 

💡  나의 풀이

import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;

class Main {
	static int N;
	static int K;
	static int max = 0;
	static String[] words;
	static boolean[] learned = new boolean['z'+1];
	static List<Character> unknown;

	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = new StringTokenizer(br.readLine());
		N = Integer.parseInt(st.nextToken());
		K = Integer.parseInt(st.nextToken()) - 5;
		words = new String[N];

		if(K < 0) {
			System.out.println(0);
			return;
		}

		for(int i=0; i<N; i++) {
			String str = br.readLine();
			words[i] = str.substring(4, str.length()-4);
		}

		learned['a'] = true;
		learned['n'] = true;
		learned['t'] = true;
		learned['i'] = true;
		learned['c'] = true;

		getUnknownChar();
		teachWords(0,0);
		System.out.println(max);
	}

	private static void teachWords(int depth, int start) {
		if(depth == Math.min(K, unknown.size())) { //K보다 unknown.size()가 작을 수 있다.
			int num = 0;
			for(int i=0; i<N; i++) {
				if(canRead(words[i])) num++;
			}
			max = Math.max(max,num);
			return;
		}

		for(int i=start; i<unknown.size(); i++) {
			char ch = unknown.get(i);
			if(learned[ch]) continue;
			learned[ch] = true;
			teachWords(depth+1, i+1);
			learned[ch] = false;
		}
	}

	private static void getUnknownChar() {
		Set<Character> set = new HashSet<>();
		for(int i=0; i<N; i++) {
			for(char ch: words[i].toCharArray()) {
				if(!learned[ch]) set.add(ch);
			}
		}
		unknown = new ArrayList<>(set);
	}

	private static boolean canRead(String str) {
		for(char ch: str.toCharArray()) {
			if(!learned[ch]) return false;
		}
		return true;
	}
}

 

 


 

 

1062번: 가르침

첫째 줄에 단어의 개수 N과 K가 주어진다. N은 50보다 작거나 같은 자연수이고, K는 26보다 작거나 같은 자연수 또는 0이다. 둘째 줄부터 N개의 줄에 남극 언어의 단어가 주어진다. 단어는 영어 소문

www.acmicpc.net

 

반응형