結果
問題 | No.3 ビットすごろく |
ユーザー |
![]() |
提出日時 | 2018-05-31 01:00:53 |
言語 | C++14 (gcc 13.3.0 + boost 1.87.0) |
結果 |
AC
|
実行時間 | 50 ms / 5,000 ms |
コード長 | 1,318 bytes |
コンパイル時間 | 915 ms |
コンパイル使用メモリ | 85,840 KB |
実行使用メモリ | 6,948 KB |
最終ジャッジ日時 | 2024-07-01 09:01:25 |
合計ジャッジ時間 | 2,569 ms |
ジャッジサーバーID (参考情報) |
judge1 / judge5 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
other | AC * 33 |
ソースコード
#include <algorithm> #include <bitset> #include <iostream> #include <queue> #include <sstream> #include <string> #include <utility> #include <vector> using namespace std; int dist(int x, int y) { return (x > y) ? (x - y) : (y - x); } int count(int n) { int cnt = 0; stringstream ss; ss << static_cast<bitset<16> >(n); string s = ss.str(); for (auto itr = s.begin(); itr != s.end(); itr++) { if (*itr == '1') cnt++; } return cnt; } bool in(vector<int> v, int n) { for (auto& var : v) { if (var == n) return true; } return false; } int solve(int n) { queue<pair<int, int> > q; // <位置, 歩数> q.push(make_pair(1, 1)); vector<int> v; v.push_back(1); // 行ったことがある数字を覚えておく while (!q.empty()) { pair<int, int> tmp = q.front(); int num = tmp.first; int cnt = tmp.second; q.pop(); if (num == n) return cnt; int forward = num + count(num); int backward = num - count(num); if (!(in(v, forward)) && (forward <= n)) { q.push(make_pair(forward, cnt + 1)); v.push_back(forward); } if (!(in(v, backward)) && (backward > 0)) { q.push(make_pair(backward, cnt + 1)); v.push_back(backward); } } return -1; } int main() { int n; cin >> n; cout << solve(n) << endl; return 0; }