가르침 성공
시간 제한메모리 제한제출정답맞힌 사람정답 비율
1 초 | 128 MB (하단 참고) | 33774 | 9163 | 5402 | 25.135% |
문제
남극에 사는 김지민 선생님은 학생들이 되도록이면 많은 단어를 읽을 수 있도록 하려고 한다. 그러나 지구온난화로 인해 얼음이 녹아서 곧 학교가 무너지기 때문에, 김지민은 K개의 글자를 가르칠 시간 밖에 없다. 김지민이 가르치고 난 후에는, 학생들은 그 K개의 글자로만 이루어진 단어만을 읽을 수 있다. 김지민은 어떤 K개의 글자를 가르쳐야 학생들이 읽을 수 있는 단어의 개수가 최대가 되는지 고민에 빠졌다.
남극언어의 모든 단어는 "anta"로 시작되고, "tica"로 끝난다. 남극언어에 단어는 N개 밖에 없다고 가정한다. 학생들이 읽을 수 있는 단어의 최댓값을 구하는 프로그램을 작성하시오.
입력
첫째 줄에 단어의 개수 N과 K가 주어진다. N은 50보다 작거나 같은 자연수이고, K는 26보다 작거나 같은 자연수 또는 0이다. 둘째 줄부터 N개의 줄에 남극 언어의 단어가 주어진다. 단어는 영어 소문자로만 이루어져 있고, 길이가 8보다 크거나 같고, 15보다 작거나 같다. 모든 단어는 중복되지 않는다.
출력
첫째 줄에 김지민이 K개의 글자를 가르칠 때, 학생들이 읽을 수 있는 단어 개수의 최댓값을 출력한다.
예제 입력 1 복사
3 6
antarctica
antahellotica
antacartica
예제 출력 1 복사
2
예제 입력 2 복사
2 3
antaxxxxxxxtica
antarctica
예제 출력 2 복사
0
예제 입력 3 복사
9 8
antabtica
antaxtica
antadtica
antaetica
antaftica
antagtica
antahtica
antajtica
antaktica
예제 출력 3 복사
3
출처
package boj1062;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
static int N;
static int M;
static int count;
static int answer;
static int[] ext = new int[26];
static String[] arr = new String[51];
static boolean[] alpha = new boolean[26];
static boolean[] used = new boolean[27];
public static void main(String[] args) throws IOException {
// System.setIn(new FileInputStream("input.txt"));
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String[] s = in.readLine().split(" ");
N = Integer.parseInt(s[0]);
M = Integer.parseInt(s[1]);
for (int i = 0; i < N; i++) {
String str = in.readLine();
arr[i] = str;
for (int j = 0; j < str.length(); j++) {
int idx = (int) arr[i].charAt(j) - 'a';// 알파벳
if (alpha[idx] == false) {
alpha[idx] = true;
ext[count++] = idx;
}
}
}
comb(0, 0);
System.out.println(answer);
}
private static void comb(int start, int cnt) {
if(M>count) {
int cnt1 = 0;
for (int i = 0; i < N; i++) {
boolean flag = true;
for (int j = 0; j < arr[i].length(); j++) {
int numc = (int) (arr[i].charAt(j) - 'a');
if (used[numc] == false) {
flag = false;
break;
}
}
if (flag)
cnt1++;
}
if (answer < cnt1)
answer = cnt1;
}
else {
if (cnt == M) {
int cnt1 = 0;
for (int i = 0; i < N; i++) {
boolean flag = true;
for (int j = 0; j < arr[i].length(); j++) {
int numc = (int) (arr[i].charAt(j) - 'a');
if (used[numc] == false) {
flag = false;
break;
}
}
if (flag)
cnt1++;
}
if (answer < cnt1)
answer = cnt1;
return;
}
}
for (int i = start; i < count; i++) {
if (used[ext[i]] == true)
continue;
used[ext[i]] = true;
comb(i + 1, cnt + 1);
used[ext[i]] = false;
}
}
}
오랜만에 돌아왔습니다.. 싸피하면서 언어는 자바로 전향했고, 순조부를 많이 풀고있습니다 ㅋ