[1620] 나는야 포켓몬 마스터 이다솜

RudinP·2023년 4월 10일
0

BaekJoon

목록 보기
30/77

문제는 딱히 복사해오지 않겠습니다...

입력

  • 첫째 줄에는 도감에 수록되어 있는 포켓몬의 개수 N이랑 내가 맞춰야 하는 문제의 개수 M이 주어져. N과 M은 1보다 크거나 같고, 100,000보다 작거나 같은 자연수인데, 자연수가 뭔지는 알지? 모르면 물어봐도 괜찮아. 나는 언제든지 질문에 답해줄 준비가 되어있어.
    둘째 줄부터 N개의 줄에 포켓몬의 번호가 1번인 포켓몬부터 N번에 해당하는 포켓몬까지 한 줄에 하나씩 입력으로 들어와. 포켓몬의 이름은 모두 영어로만 이루어져있고, 또, 음... 첫 글자만 대문자이고, 나머지 문자는 소문자로만 이루어져 있어. 아참! 일부 포켓몬은 마지막 문자만 대문자일 수도 있어. 포켓몬 이름의 최대 길이는 20, 최소 길이는 2야. 그 다음 줄부터 총 M개의 줄에 내가 맞춰야하는 문제가 입력으로 들어와. 문제가 알파벳으로만 들어오면 포켓몬 번호를 말해야 하고, 숫자로만 들어오면, 포켓몬 번호에 해당하는 문자를 출력해야해. 입력으로 들어오는 숫자는 반드시 1보다 크거나 같고, N보다 작거나 같고, 입력으로 들어오는 문자는 반드시 도감에 있는 포켓몬의 이름만 주어져. 그럼 화이팅!!!

출력

  • 첫째 줄부터 차례대로 M개의 줄에 각각의 문제에 대한 답을 말해줬으면 좋겠어!!!. 입력으로 숫자가 들어왔다면 그 숫자에 해당하는 포켓몬의 이름을, 문자가 들어왔으면 그 포켓몬의 이름에 해당하는 번호를 출력하면 돼. 그럼 땡큐~

생각

Dictionary<int, string> 으로, 1번부터 증가한다는 것을 유의한다.
입력받은 것에 대해 타입을 검사하고, 해당하는 답을 출력하도록 한다.

밸류값으로 역으로 키값을 찾는 것은 이 글을 참고하였다. (FirstOrDefault)

처음 코드

namespace SongE
{
    public class Program
    {
        static void Main(string[] args)
        {
            using var input = new System.IO.StreamReader(Console.OpenStandardInput());
            using var print = new System.IO.StreamWriter(Console.OpenStandardOutput());

            Dictionary<int, string> pokemon = new();
            int[] n = Array.ConvertAll(input.ReadLine().Split(), s => int.Parse(s));

            for(int i = 1; i <= n[0]; i++)
            {
                pokemon.Add(i, input.ReadLine());
            }

            for(int i = 0; i < n[1]; i++)
            {
                string q = input.ReadLine();
                if (int.TryParse(q, out int qInt))
                {
                    print.WriteLine(pokemon[int.Parse(q)]);
                }
                else
                {
                    //밸류값으로 키값 찾기
                    print.WriteLine(pokemon.FirstOrDefault(entry => EqualityComparer<string>.Default.Equals(entry.Value, q)).Key);
                }
            }

        }
    }
}

시간초과가 났다.

두번째 코드

using System.Text;

namespace SongE
{
    public class Program
    {
        static void Main(string[] args)
        {
            using var input = new System.IO.StreamReader(Console.OpenStandardInput());
            using var print = new System.IO.StreamWriter(Console.OpenStandardOutput());

            StringBuilder sb = new StringBuilder();
            Dictionary<int, string> pokemon = new();
            int[] n = Array.ConvertAll(input.ReadLine().Split(), s => int.Parse(s));

            for(int i = 1; i <= n[0]; i++)
            {
                pokemon.Add(i, input.ReadLine());
            }

            for(int i = 0; i < n[1]; i++)
            {
                string q = input.ReadLine();
                if (int.TryParse(q, out int qInt))
                {
                    sb.AppendLine(pokemon[qInt]);
                }
                else
                {
                    //밸류값으로 키값 찾기
                    sb.AppendLine($"{pokemon.FirstOrDefault(x => x.Value == q).Key}");
                }
            }

            print.WriteLine(sb.ToString());
        }
    }
}

시간 초 과

여기서 학원선생님께 여쭤봐서 어느 부분이 문제일까 여쭈어봤더니, 밸류값으로 찾는 것은 시간 코스트가 많이 든다고 하셨다. 메모리 문제가 없다면 그냥 딕셔너리를 두개를(서로 키값과 밸류값이 반대인) 만들어보라고 하셨고, 해결되었다.

최종 코드

using System.Text;

namespace SongE
{
    public class Program
    {
        static void Main(string[] args)
        {
            using var input = new System.IO.StreamReader(Console.OpenStandardInput());
            using var print = new System.IO.StreamWriter(Console.OpenStandardOutput());

            StringBuilder sb = new StringBuilder();
            Dictionary<int, string> pokemon = new();
            Dictionary<string, int> pokemon2 = new();
            int[] n = Array.ConvertAll(input.ReadLine().Split(), s => int.Parse(s));

            for(int i = 1; i <= n[0]; i++)
            {
                string s = input.ReadLine();
                pokemon.Add(i, s);
                pokemon2.Add(s, i);
            }

            for(int i = 0; i < n[1]; i++)
            {
                string q = input.ReadLine();
                if (int.TryParse(q, out int qInt))
                {
                    sb.AppendLine(pokemon[qInt]);
                }
                else
                {
                    //밸류값으로 키값 찾기
                    sb.AppendLine($"{pokemon2[q]}");
                }
            }

            print.WriteLine(sb.ToString());
        }
    }
}

허망하군요... 확실히 그 부분이 많이 걸릴거같아서 좀 고쳤었는데 그냥 밸류값으로 찾는게 코스트가 많이 드는구나

profile
곰을 좋아합니다. <a href = "https://github.com/RudinP">github</a>

0개의 댓글