結果

問題 No.3 ビットすごろく
ユーザー koyumeishikoyumeishi
提出日時 2014-11-17 20:55:11
言語 C++11
(gcc 11.4.0)
結果
AC  
実行時間 4 ms / 5,000 ms
コード長 1,674 bytes
コンパイル時間 766 ms
コンパイル使用メモリ 84,000 KB
実行使用メモリ 4,380 KB
最終ジャッジ日時 2023-09-13 22:55:39
合計ジャッジ時間 2,045 ms
ジャッジサーバーID
(参考情報)
judge11 / judge15
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 2 ms
4,380 KB
testcase_01 AC 2 ms
4,376 KB
testcase_02 AC 1 ms
4,380 KB
testcase_03 AC 2 ms
4,380 KB
testcase_04 AC 2 ms
4,376 KB
testcase_05 AC 3 ms
4,380 KB
testcase_06 AC 2 ms
4,376 KB
testcase_07 AC 2 ms
4,380 KB
testcase_08 AC 2 ms
4,380 KB
testcase_09 AC 3 ms
4,376 KB
testcase_10 AC 3 ms
4,376 KB
testcase_11 AC 3 ms
4,380 KB
testcase_12 AC 3 ms
4,380 KB
testcase_13 AC 2 ms
4,380 KB
testcase_14 AC 3 ms
4,376 KB
testcase_15 AC 3 ms
4,376 KB
testcase_16 AC 3 ms
4,380 KB
testcase_17 AC 3 ms
4,376 KB
testcase_18 AC 2 ms
4,376 KB
testcase_19 AC 3 ms
4,376 KB
testcase_20 AC 1 ms
4,380 KB
testcase_21 AC 1 ms
4,380 KB
testcase_22 AC 3 ms
4,376 KB
testcase_23 AC 3 ms
4,376 KB
testcase_24 AC 4 ms
4,380 KB
testcase_25 AC 3 ms
4,380 KB
testcase_26 AC 1 ms
4,380 KB
testcase_27 AC 2 ms
4,380 KB
testcase_28 AC 3 ms
4,376 KB
testcase_29 AC 3 ms
4,376 KB
testcase_30 AC 2 ms
4,376 KB
testcase_31 AC 2 ms
4,376 KB
testcase_32 AC 2 ms
4,376 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <iostream>
#include <vector>
#include <cstdio>
#include <sstream>
#include <map>
#include <string>
#include <algorithm>
#include <queue>
#include <cmath>

using namespace std;
#include <vector>
#include <algorithm>
#include <queue>
#include <cmath>

using namespace std;

#define INF 10000000
 
typedef struct{
	int to;
	int cost;
}edge;

//distance from s
//O(E log V)
void dijkstra(vector<vector<edge> > &G, vector<int> &dist, int s){
	//first : distance from s, second : its vertex
	priority_queue< pair<int,int> , vector<pair<int,int> >, greater< pair<int,int> > > pq;
	 
	fill(dist.begin(), dist.end(), INF);
	dist[s] = 0;
	pq.push( make_pair(dist[s], s) );
	while(!pq.empty()){
		pair<int,int> q = pq.top();
		pq.pop();
		int from = q.second;
		if(dist[from] < q.first) continue; // it's not minimum distance
		int n=G[from].size();
		for(int i=0; i<n; i++){
			edge e = G[from][i];
			if(dist[e.to] > dist[from] + e.cost){
				dist[e.to] = dist[from] + e.cost;
				pq.push( make_pair(dist[e.to], e.to) );
			}
		}
	}
}
 
void add_edge(vector<vector<edge> > &G, int from, int to, int cost){
	G[from].push_back( (edge){to, cost} );
	//G[to].push_back( (edge){from, cost} );
}


int bits(int n){
	int ret = 0;
	while( n>0 ){
		ret++;
		n -= n&-n;
	}
	return ret;
}

int main(){
	int n;
	cin >> n;
	
	vector<vector<edge> > G(n+1);
	
	for(int i=1; i<=n; i++){
		int d = bits(i);
		if(i-d > 0) add_edge(G, i, i-d, 1);
		if(i+d <= n) add_edge(G, i, i+d, 1);
	}

	vector<int> dist(n+1);
	dijkstra(G, dist, 1);
	int ans = (dist[n]>=INF?-1:dist[n]+1);
	cout << ans << endl;
	return 0;
}
0