Skip to content

JOI 2006-2007 予選 問題3: シーザー暗号

問題

解説

3文字シフトのシーザー暗号を復号する. 元に戻すには 26 - 3 文字さらにシフトすれば良い.

実装例

C++

cpp
#include <iostream>

std::string caesar_cipher(std::string &s, int n) {
  char table[0xff] = {0};

  for (int t = 0; t < 0xff; t++) {
    table[t] = t;
  }

  for (int i = 0; i < 26; i++) {
    char upper_ch_src = 'A' + i;
    char upper_ch_dst = 'A' + (i + n) % 26;
    char lower_ch_src = 'a' + i;
    char lower_ch_dst = 'a' + (i + n) % 26;

    table[(int)upper_ch_src] = upper_ch_dst;
    table[(int)lower_ch_src] = lower_ch_dst;
  }

  std::string res = "";
  for (int i = 0; i < (int)s.size(); i++) {
    char ch = s[i];
    res += table[(int)ch];
  }

  return res;
}

int main() {
  std::cin.tie(0);
  std::ios_base::sync_with_stdio(false);

  std::string cipher_text;

  std::cin >> cipher_text;
  std::cout << caesar_cipher(cipher_text, 26 - 3) << "\n";

  return 0;
}

Python

python
#!/usr/bin/env python3


def caesar_cipher(s, n):
    d = {}
    for c in (65, 97):
        for i in range(26):
            d[chr(i + c)] = chr((i + n) % 26 + c)

    return "".join([d.get(c, c) for c in s])


cipher_text = input()
plain_text = caesar_cipher(cipher_text, 26 - 3)

print(plain_text)