IT・ビッグデータ徒然ブログ

関西でインフラ、データ基盤系のエンジニアになりたい

AtCoderに登録したら解くべき精選過去問10問の類題をC++で解いてみた(その2)

前回の続き。
ABC 081 A - Placing Marbles の類題を解いていく。

ABC 079 A - Good Integer

  • 4桁中上3桁または下3桁が同じ値であるか判別
  • 数値を文字列として扱う
  • 2桁目をcheck用にセットし、1と3桁目、または3と4桁目と同値かどうか調べる。
#include <iostream>

using namespace std;

int main() {

    string integer;
    char checkValue;
    
    
    cin >> integer;

    checkValue = integer[1];



    if((integer[0] == checkValue && integer[2] == checkValue) || (integer[2] == checkValue && integer[3] == checkValue)) {
        cout << "Yes" << endl;
    } else {
        cout << "No" << endl;
    }

    return 0;
}

ABC 085 A - Already 2018

  • 文字列の一部を書き換える
  • 意外とC++が一番簡単に書けるのでは??
#include <iostream>

using namespace std;

int main() {

    string date;

    cin >> date;

    date[3] = '8';

    cout << date << endl;

    return 0;
}

ABC 069 B - i18n

  • 文字列から真ん中の文字を文字数に変換する
  • C++だと文字列を配列として取れるので、文字数を取得したあと、
    • 最初の文字
    • 最後の文字
    • 真ん中の文字数を取得
  • そのあと文字列の結合を実行
#include <iostream>
#include <string>

using namespace std;

int main() {

    string str,first,last,out;
    int strlength,middle;

    cin >> str;

    strlength = str.length();

    first = str[0];
    middle = strlength - 2;
    last = str[strlength - 1];

    out = first + to_string(middle) + last;

    cout << out << endl;



    return 0;
}

ABC 082 B - Two Anagrams

  • 入力した2つの文字列をソート
  • その際、1つ目は文字が小さい順(a to z)に、2つ目は大きい順(z to a)に並び替える・
  • ソート後文字列を比較して2つ目のほうが辞書的に後の文字ならYes、逆ならNoと回答
  • 全く同じ文字同士の比較が続いた場合、文字数が多いほうが辞書的に後になるので、文字数を比較したbool型のflag変数を使ってYes,Noを選択
  • (変数の設定が汚いのはお許しください・・・(というより、よりよい変数の付け方を勉強しないと))
#include <iostream>
#include <string>
#include <algorithm>
 
using namespace std;
 
int main() {
 
    string anagram1,anagram2;
    int anagram1_size,anagram2_size;
    bool flag;
 
    cin >> anagram1;
    cin >> anagram2;
 
 
    anagram1_size = anagram1.length();
    anagram2_size = anagram2.length();

    flag = anagram1_size < anagram2_size; 

    sort(anagram1.begin(),anagram1.end());
    sort(anagram2.begin(),anagram2.end(),greater<int>());
    
    for(int i = 0 ; i < min(anagram1_size,anagram2_size); i++) {
        if(anagram1[i] < anagram2[i]) {
            cout << "Yes" << endl;
            return 0;
        } else if (anagram1[i] > anagram2[i]) {
            cout << "No" << endl;
            return 0;
        }
    }
    
    if(flag) {
        cout << "Yes" << endl;
    } else {
        cout << "No" << endl;
    }
 
    return 0;
}