1. 문제

20920번: 영단어 암기는 괴로워



2. 개요

영단어를 암기하기 위해 영어 단어장을 만들려고 한다.

단어장의 단어 순서는 다음과 같은 기준에 따라 정렬된다.

  1. 자주 나오는 단어일수록 앞에 배치한다.
  2. 해당 단어의 길이가 길수록 앞에 배치한다.
  3. 알파벳 사전 순으로 앞에 있는 단어일수록 앞에 배치한다

M보다 짧은 길이의 단어는 보자마자 기억할 수 있기 때문에 단어장에 추가하지 않는다.

N, M과 단어들이 주어졌을 때 단어장에 실린 순서대로 단어를 출력하는 문제.



3. 풀이 및 코드

3-1. 풀이

단어의 등장 횟수를 셀 Dictionary와 단어를 실제로 실을 단어장을 List로 각각 만들어둔다.

단어 입력을 받을 때 마다 단어의 길이가 M보다 작다면 건너뛴다.

M 이상이라면 Dictionary안에 존재하는지 여부를 파악한다. 존재하지 않는다면 1로 만들어주면서 List에 추가하고, 존재한다면 value값만 1만큼 늘려준다.

모든 단어 입력을 받았다면 리스트를 정렬한다.

Dictionary의 value값의 내림차순, 단어의 길이의 내림차순, 사전 순 순서대로 정렬을 진행한 뒤 한 줄에 하나씩 단어들을 출력한다.

3-2. Python

import sys

N, M = map(int, sys.stdin.readline().split())

vocadict = dict()
vocas = []

for i in range(N):
    v = sys.stdin.readline().rstrip()

    if len(v) < M:
        continue

    if v not in vocadict:
        vocadict[v] = 1
        vocas.append(v)

    else:
        vocadict[v] += 1

vocas.sort(key = lambda x : (-vocadict[x], -len(x), x))

for voca in vocas:
    print(voca)

3-3. C#

namespace boj_20920
{
    internal class Program
    {
        static void Main(string[] args)
        {
            StreamReader sr = new StreamReader(Console.OpenStandardInput());
            StreamWriter sw = new StreamWriter(Console.OpenStandardOutput());

            string[] input = sr.ReadLine().Split();
            int N = int.Parse(input[0]);
            int M = int.Parse(input[1]);

            Dictionary<string, int> vocadict = new Dictionary<string, int>();
            List<string> vocas = new List<string>();

            for (int i = 0; i < N; i++)
            {
                string v = sr.ReadLine();

                if (v.Length < M)
                    continue;

                if (vocadict.ContainsKey(v))
                    vocadict[v]++;

                else
                {
                    vocadict[v] = 1;
                    vocas.Add(v);
                }
            }

            vocas = vocas.OrderBy(x => (-vocadict[x], -x.Length, x)).ToList();

            foreach (string voca in vocas)
                sw.WriteLine(voca);

            sw.Close();
        }
    }
}

Comments