yukicoder no.3 ビットすごろく

問題文
http://ch.nicovideo.jp/programing/blomaga/ar583624

解答
__builtin_popcount() + 幅優先探索 する。最短経路問題である。

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

int main() {
  
  int N; cin >> N;
  
  int const INF = 1<<29;
  bool vis[10001] = {};
  queue<pair<int, int> > q;
  q.push(make_pair(1, 1));
  while(!q.empty()) {
    int now = q.front().first;
    int cost = q.front().second; q.pop();
    
    if(now == N) {
      cout << cost << endl;
      return 0;
    }
    
    int a = now - __builtin_popcount(now);
    if(a > 0 && !vis[a]) {
      vis[a] = 1;
      q.push(make_pair(a, cost+1));
    }
    int b = now + __builtin_popcount(now);
    if(b < N+1 && !vis[b]) {
      q.push(make_pair(b, cost+1));
    }
  }
  
  cout << -1 << endl;
  
  return 0;
}