KingSort
方針
- ローマ数字の文字列 -> 整数 の変換が肝
- 'I'は基本的には1, 但し、次が'V'or'X'なら-1.
- 'X'も同様に基本的には10, 但し、次が'L'なら-10.
雑感
コードを提出した時、「このコードは、30%以上の無関係なコードを含んでいるから、Unused Code Ruleに抵触するかもしれません」という警告が出て、焦った。けど、ここで行われているチェックは、厳密なものではないらしいので、あからさまに違反している時以外は無視すれば良いっぽい。実際、メッセージでも"may violate"となっていた。
回答
#include <sstream> #include <string> #include <vector> #include <map> #include <algorithm> #include <iostream> #include <utility> #include <set> #include <cctype> #include <queue> #include <stack> #include <cstdio> #include <cstdlib> #include <cmath> #include <iterator> using namespace std; class KingSort{ public: static int tonum2(const char x, const char next){ int ret; if(x == 'I'){ if(next == 'V' || next == 'X') ret = -1; else ret = 1; } if(x == 'V') ret = 5; if(x == 'X'){ if(next == 'L') ret = -10; else ret = 10; } if(x == 'L') ret = 50; return ret; } static int tonum(const string& romen){ int ret = 0; for(size_t i = 0; i < romen.size(); ++i){ ret += KingSort::tonum2(romen[i], (i+1)==romen.size() ? 0 : romen[i+1]); } return ret; } static bool comp(const string& x, const string& y){ stringstream sstx(x), ssty(y); string namex, namey; sstx >> namex; ssty >> namey; string numx, numy; sstx >> numx; ssty >> numy; if(namex == namey) return KingSort::tonum(numx) < KingSort::tonum(numy); else return namex < namey; } vector <string> getSortedList(vector <string> kings){ sort(kings.begin(), kings.end(), KingSort::comp); return kings; } };