備忘録

まとめておきたいことのメモ 主にプロコンのこと

AOJ-ICPC 2252

今日といたのはこの問題。

koukyoukoukokukikou | Aizu Online Judge

ある文字列を打つとき、QWERTY配列のキーボードを用いた場合使う手が左手と右手と入れ替える回数を数えよう!という問題。

答えはこちら。

#include <cstdio>
#include <iostream>
#include <cmath>
#include <ctype.h>
#include <string> 
#include <sstream>
#include <iostream>
#include <algorithm>
#include <cstdlib>
#include <map>
#include <queue>
#include <utility>
#include <vector>
#include <set>
  
using namespace std;
 
int main()
{
    string left = "qwertasdfgzxcvb";
    string right = "yuiophjklnm";
    string input;
    while(1){
        cin >> input;
        if(input == "#") break;
        int beforehand = 1;
        // nowhand = 0/right, 1/left
        for(int j = 0; j < right.length(); j++){
                if(right[j] == input[0]){
                    beforehand = 0;
                    break;
                }
            }
        int cnt = 0;
        for(int i = 0; i < input.length(); i++){
            int nowhand = 1;
            for(int j = 0; j < right.length(); j++){
                if(right[j] == input[i]){
                    nowhand = 0;
                    break;
                }
            }
            if(beforehand != nowhand){
                cnt++;
                beforehand = nowhand;
            }
        }
        cout << cnt << endl;    
    }
}

一個前の文字を打つのにどちらの手を使ったのかを保存するのがbeforehand、次の文字をうつのに使った手を保存するのがnowhandです。0のとき右手、1のとき左手を意味します。
beforehandとnowhandが異なっていたとき、cntに1を加えてbeforehandをnowhandに変更します。
これを繰り返すことで、cntが求める値と一致します。

文字列のなかから文字列を探すとき、findというものが使えるらしいですね。今回はこれを使いませんでした。
それには二つ理由があります。
一つ目は、文字列の検索ができる、とあるがchar型の1文字にも使えるかどうかはっきりわからなかった、ということ。
二つ目は、見つからなかった場合の返り値がややこしい、ということです。
そのうちきちんと調べるか実験してみるかしないといけませんね。