0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

コツコツAtCoder (ABC218 B - qwerty)

Last updated at Posted at 2022-03-20

AtCoderの過去問をコツコツ解くだけの記事です。
解いた問題全部を記事にするのは苦痛なので稀に気持ちが乗っている時だけやっていきます。

問題文

1以上26以下の整数からなる長さ 26 の数列 P=(P1,P2,P3,…,P26)が与えられます。ここで、Pの要素は相異なることが保証されます。
以下の条件を満たす長さ 26 の文字列 S を出力してください。
・任意の i(1≤i≤26)について、Sのi文字目は辞書順で小さい方からPi番目の英小文字である。

制約

  1. 1≤Pi≤26
  2. Pi≠Pj (i≠j)
  3. 入力は全て整数である。

想定入力 / 出力

例①
入力 : 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
出力 : abcdefghijklmnopqrstuvwxyz
例②
入力 : 5 11 12 16 25 17 18 1 7 10 4 23 20 3 2 24 26 19 14 9 6 22 8 13 15 21
出力 : eklpyqragjdwtcbxzsnifvhmou

回答

ABC218 B - qwerty
#include <iostream>
using namespace std;

int main() {
  int num = 97;
  int out[26];
  int p[26];
  
  for(int i=0; i<26; i++){
    cin >> p[i];
    out[i] = num+p[i]-1;
  }
  
  for(int l=0; l<26; l++){
    printf("%c",out[l]);
  }
  return 0;
}

入力される数字に対応したアルファベットの値を出力するという問題です。
これは、入力された数字が"a"からどれだけ離れているかを考えれば良いということになります。
例えば"b"は"a"から1文字分離れているので、距離は1。"e"は"a"から4文字文離れているので距離は4、みたいな感じです。

"a"は文字コードにすると0x61で、十進数にすると97です。
従って、97からどれだけ離れているかを計算して出力していけば問題なく回答することができます。

文字コードの例
a = 97
b = 98 (97+1)
C = 99 (97+2)

今回はそこそこシンプルに書いたつもりでしたが、公式の回答だと以下のようにさらにシンプルでかつ美しく記述されていました。
私はそもそも「ans += (char)('a'+p);」という記載方法を知らなかったので、C++の細かい文法を学ぶ機会も設けなきゃなぁと思いました(小学生並の感想)

公式回答
#include <bits/stdc++.h>
using namespace std;

int main(){
    string ans;
    for(int i = 0; i < 26; i++){
        int p; cin >> p; p--;
        ans += (char)('a'+p);
    }
    cout << ans << endl;
}

また、あまり美しくはないですが、アルファベットを26個格納した一次元配列を用意して、入力値-1を添字にして出力するという方法もあるかなぁと思いました。

ということで、アルゴリズムをもっと勉強していきます・・・

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?