結果

問題 No.3 ビットすごろく
ユーザー airuai
提出日時 2016-09-14 15:06:16
言語 C++11(廃止可能性あり)
(gcc 13.3.0)
結果
AC  
実行時間 154 ms / 5,000 ms
コード長 1,011 bytes
コンパイル時間 526 ms
コンパイル使用メモリ 56,748 KB
実行使用メモリ 42,528 KB
最終ジャッジ日時 2024-07-01 08:04:39
合計ジャッジ時間 2,723 ms
ジャッジサーバーID
(参考情報)
judge4 / judge5
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 33
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <iostream>
using namespace std;

#define MAX 10000000

int q[MAX];
int head = 0, tail = 0;

void enq(int p) {
	q[tail] = p;
	++tail;
	if (tail >= MAX) {
		tail = 0;
	}
}

bool deq(int* p) {
	if (head == tail) {
		return false;
	}
	else {
		*p = q[head];
		++head;
		if (head >= MAX) {
			head = 0;
		}
		return true;
	}
}

int BinaryCount(int a) {
	int cnt = 0;
	while (a>0) {
		cnt++;
		a &= a - 1;
	}
	return cnt;
}

int main(void) {
	int n;
	cin >> n;

	int* count = new int[n+1];
	for (int i = 1; i <= n; ++i) {
		count[i] = MAX;
	}

	int posi = 1, hosuu;
	count[posi] = 1;
	do {
		hosuu = BinaryCount(posi);
		if (posi - hosuu > 0 && count[posi - hosuu] > count[posi]) {
			count[posi - hosuu] = count[posi] + 1;
			enq(posi - hosuu);
		}
		if (posi + hosuu <= n && count[posi + hosuu] > count[posi]) {
			count[posi + hosuu] = count[posi] + 1;
			enq(posi + hosuu);
		}
	} while (deq(&posi));

	if (count[n] != MAX) {
		cout << count[n] << endl;
	}
	else {
		cout << "-1" << endl;
	}
	return 0;
}
0