結果

問題 No.3 ビットすごろく
ユーザー xanqh
提出日時 2023-10-26 21:24:58
言語 C++17
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 2 ms / 5,000 ms
コード長 796 bytes
コンパイル時間 1,723 ms
コンパイル使用メモリ 197,576 KB
最終ジャッジ日時 2025-02-17 13:52:00
ジャッジサーバーID
(参考情報)
judge3 / judge4
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 33
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>
using namespace std;

#define MAX 9999999

int bitcount(int bits) {
    int num  = 0;
    for ( ; bits != 0 ; bits &= bits - 1 ) {
        num++;
    }
    return num;
}

int main() {
    int N;
    cin >> N;
    vector<int> dp(N+1, MAX);
    dp[1] = 1;
    queue<int> que;
    que.push(1);
    // BFS
    while(!que.empty()) {
        int state = que.front();
        que.pop();
        int move = bitcount(state);
        for(int i=-move; i<=move; i+=move*2) {
            int next = state + i;
            if(next < 1 || next > N) continue;
            if(dp[next] != MAX) continue;
            dp[next] = dp[state] + 1;
            que.push(next);
        }
    }

    if(dp[N] == MAX) {
        cout << -1 << endl;
    } else {
        cout << dp[N] << endl;
    }
}
0