LoginSignup
1
0

More than 5 years have passed since last update.

第3回 オフラインリアルタイムどう書く解答(C++)

Last updated at Posted at 2012-09-07

オフラインリアルタイムどう書く。三度目。
問題は http://nabetani.sakura.ne.jp/hena/ord3ynode/
コードをアップするところまでが勉強会( see http://qiita.com/items/1815701039050f42bbc1 ) ということで、その場で書いた C++11 版を

ynode.cpp
#include <iostream>
#include <utility>
#include <string>
#include <map>
#include <cassert>

using namespace std;

struct testdata_t
{
  string in;
  string expected;
};
testdata_t testdata[]{
// 略
/*30*/ {"rrrrbllrlrbrbrr", "ACBACABCFDEDADFC" },
};

string turn_r{ "BACBA ADFCAD EBCFEB DABEDA FDEFD" };
string turn_l{ turn_r.rbegin(), turn_r.rend() };

string turn( string const & state, string const & course )
{
  auto pos = course.find( state );
  assert( pos != string::npos );
  return course.substr(pos+2,1);
}

string solv( string const & in )
{
  string r{"BA"};
  for( auto ch : in ){
    string state{ r.end()-2, r.end() };
    switch( ch ){
    case 'b':
      r+=state[0];
      break;
    default:
      r+=turn( state, ch=='r' ? turn_r : turn_l );
      break;
    }
  }
  return {r.begin()+1, r.end()};
}
int main()
{
  for( auto t : testdata ){
    auto actual = solv(t.in);
    cout << t.in << "->" << actual;
    if ( actual != t.expected ){
      cout << "**FAIL** expected : " << t.expected;
    }
    cout << endl;
  }
  return 0;
}

turn_r は、右に曲がり続けたらこうなるよというシーケンス。
turn_l は、左。
ということで、turn_r から "AB" を見つけ出すと、その次の文字が AB の後で右に曲がったら到達する Y字路。というロジック。

C++11 の機能をちょっと使ってだいぶ楽をしている。

1
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
1
0