Home 백준 1062번 호텔
Post
Cancel

백준 1062번 호텔

정보

문제 바로가기 [클릭]

난이도: Gold4

관련 개념: #브루트포스 #백트래킹 #비트마스킹


조건

시간 제한메모리 제한
1 초128 MB

문제

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

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


입력

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


출력

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


예제 입출력 1

입력

1
2
3
4
3 6
antarctica
antahellotica
antacartica

출력

1
2

예제 입출력 2

입력

1
2
3
2 3
antaxxxxxxxtica
antarctica

출력

1
0

예제 입출력 3

입력

1
2
3
4
5
6
7
8
9
10
9 8
antabtica
antaxtica
antadtica
antaetica
antaftica
antagtica
antahtica
antajtica
antaktica

출력

1
3

코드(파이썬)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
from itertools import combinations
from functools import reduce


antatica = {ord(c) - ord('a') for c in "antatica"}
result = 0

n, k = map(int, input().split())
words = [{ord(c) - ord('a') for c in input().rstrip()}.difference(antatica) for _ in range(n)]
all_words = reduce(lambda a, b:a.union(b), words)

if k > 4:
    if len(all_words) > k-5:
        for set_word in map(set, combinations(all_words, k-5)):
            result = max(result, sum([w.difference(set_word)==set() for w in words]))
    else:
        result = len(words)

print(result)


특이사항

  • 해결방법
    • 입력 문자열을 문자셋 리스트인 words로 변경
    • 지금 있는 모든 문자를 all_words에 저장
    • k가 4보다 크다면
      • all_words의 길이가 k-5보다 길다면 all_words의 문자들의 조합을 만들어 브루트포스로 최댓값 탐색
      • all_words의 길이가 더 짧거나 같다면 words의 길이로 최댓값
  • 내 코드(32,452KB, 4,448ms)에 비해 우수한 코드(바로가기, 30,840KB, 864ms)와 비교
    • 1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      36
      37
      38
      39
      
      from itertools import combinations
      from sys import stdin
      input = stdin.readline
      
      def solution():
          n,k = map(int, input().split())
          if k < 5:
              return 0
          k -= 5
      
          learned = set('antic')
          unlearned = set()
          cant_read_words = []
          can_read_cnt = 0
      
          for _ in range(n):
              word = set(input().rstrip()) - learned
              if word:
                  unlearned.update(word)
                  cant_read_words.append(word)
              else:
                  can_read_cnt += 1
              
          if len(unlearned) <= k:
              return n
      
          answer = 0
          for comb in combinations(unlearned,k):
              comb = set(comb)
              cnt = 0
              for word in cant_read_words:
                  if comb >= word:
                      cnt += 1
              answer = max(answer, cnt)
              
          answer += can_read_cnt
          return answer
      
      print(solution())
      
    • 큰 틀에서는 동일한 알고리즘으로 보임 -> 4배의 차이가 나는 명확한 이유 확인 필요

참고문헌

-

This post is licensed under CC BY 4.0 by the author.

백준 1106번 호텔

백준 14502번 연구소

Comments powered by Disqus.