Chinaunix首页 | 论坛 | 博客
  • 博客访问: 473777
  • 博文数量: 59
  • 博客积分: 345
  • 博客等级: 二等列兵
  • 技术积分: 1380
  • 用 户 组: 普通用户
  • 注册时间: 2011-06-18 22:44
个人简介

to be myself

文章分类

全部博文(59)

文章存档

2017年(5)

2013年(47)

2012年(3)

2011年(4)

分类: C/C++

2013-03-02 17:15:30

和poj1753类似,可能此题改变的状态比翻棋需要改变的点更多一点,如果每一位分别改变的话直接TLE.换成用数组先存状态转移量,改变状态时直接"异或"就会快很多


点击(此处)折叠或打开

  1. #include <stdio.h>

  2. #define MAX 65536

  3. typedef struct
  4. {
  5.     int state;
  6.     int step;
  7. }Queue;

  8. Queue q[MAX] = {0}; //状态队列
  9. int vis[MAX] = {0}; //判重数组
  10. int fa[MAX] = {0}; //记录父状态
  11. int fa_step[MAX]={0}; //父状态转移到子状态的步骤

  12. //状态转移量
  13. int change[16]=
  14. {
  15.     0x111F, 0x222F, 0x444F, 0x888F,
  16.     0x11F1, 0x22F2, 0x44F4, 0x88F8,
  17.     0x1F11, 0x2F22, 0x4F44, 0x8F88,
  18.     0xF111, 0xF222, 0xF444, 0xF888
  19. };

  20. /*************************************
  21. |func:递归反向输出成功得到结果的步骤
  22. |args:当前状态cur
  23. |retn:无返回
  24. *************************************/
  25. void OutPut(int cur)
  26. {

  27.     if (-1 != fa[cur])
  28.     {
  29.         OutPut(fa[cur]);
  30.     }
  31.     if (-1 != fa_step[cur])
  32.     {
  33.         printf("%d %dn", 4 - fa_step[cur] / 4, 4 - fa_step[cur] % 4);
  34.     }
  35. }

  36. int main()
  37. {
  38.     int i = 0, cur_state = 0, front = -1, rear = 0;
  39.     char c;
  40.     
  41.     while(i++ < 16)
  42.     {
  43.         c = getchar();
  44.         cur_state += (c == '+' ? 0 : 1);
  45.         cur_state <<= 1;
  46.         if (0 == i % 4)
  47.         {
  48.             getchar();
  49.         }
  50.     }
  51.     cur_state >>= 1;
  52.     
  53.     q[rear].state = cur_state;
  54.     vis[cur_state] = 1;
  55.     fa[cur_state] = -1;
  56.     fa_step[cur_state] = -1;
  57.     
  58.     while(front < rear)
  59.     {
  60.         front = (front + 1) % MAX;
  61.         if (0xFFFF == q[front].state)
  62.         {
  63.             printf("%dn", q[front].step);
  64.             break;
  65.         }
  66.         
  67.         for (i=1; i<17; i++)
  68.         {
  69.             cur_state = q[front].state;
  70.             cur_state ^= change[16-i];
  71.             if (!vis[cur_state])
  72.             {
  73.                 vis[cur_state] = 1;
  74.                 rear = (rear + 1) % MAX;
  75.                 q[rear].state = cur_state;
  76.                 q[rear].step = q[front].step + 1;
  77.                 fa[cur_state] = q[front].state;
  78.                 fa_step[cur_state] = 16 - i;
  79.             }
  80.         }
  81.     }
  82.     //从终了状态递归查找父状态
  83.     OutPut(0xFFFF);
  84.     
  85.     return 0;
  86. }

     Source Code
     
     Problem: 2965  User: angrad 
     Memory: 1404K  Time: 266MS 
     Language: C  Result: Accepted 


2011-03-22 22:10 发表于百度空间,今搬至CU。




阅读(1397) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~