Guest User

Untitled

a guest
May 25th, 2018
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.62 KB | None | 0 0
  1. #include <cstdio>
  2. #include <queue>
  3. #include <set>
  4. #include <queue>
  5. using namespace std;
  6.  
  7. using ll = long long;
  8. int dy[4] = {1,0,-1,0}, dx[4] = {0,1,0,-1};
  9. int shift[4] = {-12,-4,12,4};
  10.  
  11. int main() {
  12. ll start = 0, dest = 0;
  13. for(int i=0; i<9; ++i) {
  14. ll a;
  15. scanf("%lld",&a);
  16. start += (a<<i*4);
  17. }
  18.  
  19. for(int i=1; i<9; ++i) {
  20. dest += ((ll)i<<(4 * (i-1)));
  21. }
  22.  
  23. set<ll> visited;
  24. queue<ll> q;
  25. q.push(start);
  26. int ret = 0;
  27. while(!q.empty()) {
  28. ll qs = q.size();
  29. while(qs--) {
  30. ll cur = q.front();
  31. q.pop();
  32. if(cur == dest) {
  33. printf("%d\n",ret);
  34. return 0;
  35. }
  36. ll pos0 = 0;
  37. for(;cur & (15LL << pos0 * 4); pos0++);
  38. ll y = pos0/3, x = pos0%3;
  39. // printf("%lld %lld\n",r,c);
  40. for(int i=0; i<4; ++i) {
  41. ll ny = y + dy[i], nx = x + dx[i];
  42. if(ny < 0 || ny >= 3 || nx < 0 || nx >= 3) continue;
  43. //temp: 0으로 만들고자 하는 위치의 cur의 bit
  44. ll temp = cur & (15LL <<(ny*3+nx)*4);
  45. //cur의 0000 부분과 다음 상태의 0000부분이 0000인 상태
  46. ll next = cur - temp;
  47. //
  48. if(shift[i] > 0) temp <<= shift[i];
  49. else temp >>= -shift[i];
  50.  
  51. next += temp;
  52. if(visited.find(next) == visited.end()) {
  53. visited.insert(next);
  54. q.push(next);
  55. }
  56. }
  57. }
  58. ++ret;
  59. }
  60. puts("-1");
  61. }
Add Comment
Please, Sign In to add comment