본문 바로가기
알고리즘/백준 BOJ

[ BOJ/C# ] 1620 나는야 포켓몬 마스터 이다솜

by 왹져박사 2023. 9. 9.
728x90

https://www.acmicpc.net/problem/1620

 

1620번: 나는야 포켓몬 마스터 이다솜

첫째 줄에는 도감에 수록되어 있는 포켓몬의 개수 N이랑 내가 맞춰야 하는 문제의 개수 M이 주어져. N과 M은 1보다 크거나 같고, 100,000보다 작거나 같은 자연수인데, 자연수가 뭔지는 알지? 모르면

www.acmicpc.net

 

Dictionary와 시간복잡도를 고려하여 푸는 문제다. 시간초과로 많은 시도를 했다. 

1. 빠른 입출력 사용_StreamWriter와 StringBuilder로 빠른 출력이 되도록 함

2. sb.AppendLine이 아닌 '\n'이 빠르다. 

3. 각각 int, string가 key인 Dictionary를 두 개 만들어줌

  _처음에는 하나로 만들어 int인 key를 가져올 때 foreach 반복문이나 FirstOrDefault를 썼지만 시간초과. 

 

using System;
using System.Text;

namespace B1620
{
    class Program
    {
        static void Main()
        {
            StreamReader sr = new StreamReader(Console.OpenStandardInput());
            StreamWriter sw = new StreamWriter(Console.OpenStandardOutput());
            StringBuilder sb = new StringBuilder();

            int[] nm = Array.ConvertAll(sr.ReadLine().Split(' '), int.Parse);

            //주어진 포켓몬 저장
            Dictionary<int, string> dicInt = new Dictionary<int, string>();
            Dictionary<string, int> dicStr = new Dictionary<string, int>();
            for(int i = 0; i < nm[0]; i++)
            {
                string input = sr.ReadLine();
                dicInt.Add(i + 1, input);
                dicStr.Add(input, i + 1);
            }

            //문제
            for (int i = 0; i < nm[1]; i++)
            {
                string str = sr.ReadLine();
                int num;
                int strToInt;
                string intToStr;

                bool isInt = int.TryParse(str, out num);    //int인지 판별
                if (isInt)  //int라면 value 가져오기
                {
                    dicInt.TryGetValue(num, out intToStr);
                    sb.Append(intToStr);
                }
                else    //string이라면 int 가져오기
                {
                    dicStr.TryGetValue(str, out strToInt);
                    sb.Append(strToInt);
                }
                sb.Append('\n');
            }
            sw.Write(sb);
            sr.Close();
            sw.Flush();
            sw.Close();
        }
    }
}

728x90