1. 문제

1394번: 암호



2. 개요

어떤 암호가 있고, 문자의 집합이 있다.

문자 집합의 순서대로 하나씩 대입하면서 암호를 풀려 할 때, 몇 번째 시도만에 암호가 풀리는지 구하는 문제.



3. 풀이 및 코드

3-1. 풀이

문자 집합을 딕셔너리로 만들어 어떤 문자가 몇 번째 수인지 저장해둔다.

이후 처음에는 스택을 이용해 뒤 문자부터 빼내면서 암호 길이 ** 인덱스 * 문자 번호를 더해가며 풀어보려 했으나 시간초과로 해결할 수 없었다.

다음으로 다른 규칙을 찾아서 해결했다.

암호에서 현재 인덱스가 i라고 할 때, i-1까지의 암호 * 문자 집합의 길이 + i번째 문자의 순서가 해당 암호의 순서가 된다.

이를 이용해 해결했다.

3-2. Python

import sys

chars = sys.stdin.readline().rstrip()
length = len(chars)

cdic = dict()
for i in range(length):
    cdic[chars[i]] = i + 1

password = sys.stdin.readline().rstrip()

answer = cdic[password[0]]
idx = 1

while idx < len(password):
    answer = (answer * length + cdic[password[idx]]) % 900528
    idx += 1

print(answer)

3-3. C#

namespace boj_1394
{
    internal class Program
    {
        static void Main(string[] args)
        {
            string chars = Console.ReadLine().TrimEnd();
            int len = chars.Length;

            Dictionary<char, int> cdic = new Dictionary<char, int>();

            for (int i = 0; i < len; i++)
            {
                cdic.Add(chars[i], i + 1);
            }

            string password = Console.ReadLine().TrimEnd();

            long answer = cdic[password[0]];
            int idx = 1;

            while (idx < password.Length)
            {
                answer = answer * len + cdic[password[idx]];
                idx++;
            }

            Console.WriteLine(answer);
        }
    }
}

Comments