zoukankan      html  css  js  c++  java
  • POJ 1753 bfs+位运算

    T_T ++运算符和+1不一样。(i+1)%4 忘带小括号了。bfs函数是bool 型,忘记返回false时的情况了。噢。。。。debug快哭了。。。。。。

    DESCRIPTION:
    求最少的步骤。使得棋盘上的棋子全黑或者全白。奇数次相当于1次。偶数次相当于不翻。

    bfs用来求解最优问题。主要用来求距离初始状态路径最短的路径。思想是暴力枚举+位运算。第一次做位运算的题目。。醉醉的啦。。。。。。

    附代码:

    #include<stdio.h>
    #include<string.h>
    #include<iostream>
    #define end1 65535
    #define end2 0
    using namespace std;

    int step[end1];
    bool used[end1];
    unsigned short q[end1];
    int front = 0, rear = 0;

    void init()
    {
        char str;
        front = 0, rear = 0;
        unsigned short int begin = 0;
        for (int i=0; i<4; ++i)
        {
            for (int j=0; j<4; ++j)
            {
                cin >> str;
                if (str == 'b')
                   begin |= (1 << (i*4 + j));
            }
        }
        memset(step, 0, sizeof(step));
        memset(used, 0, sizeof(used));
        q[rear++] = begin;
        used[begin] = 1;
        step[begin] = 0;
    }

    unsigned short int move(unsigned short int state, int i)
    {
        unsigned short int temp = 0;
        temp |= (1 << i);
        if ((i + 1) % 4 != 0)
            temp |= (1 << (i + 1));
        if (i % 4 != 0)
            temp |= (1 << (i - 1));
        if (i + 4 < 16)
            temp |= (1 << (i + 4));
        if (i - 4 >= 0)
            temp |= (1 << (i - 4));
        return (state^temp);
    }

    bool bfs()
    {
         while (front < rear)
         {
             unsigned short state = q[front++];
             for (int i=0; i<16; ++i)
             {
                 unsigned short temp;
                 temp = move(state, i);
                if(0 == state || 65535 == state)
                {
                  cout << step[state];
                  return true;
                }
                 else if (!used[temp])
                 {
                     q[rear++] = temp;
                     used[temp] = true;
                     step[temp] = step[state]+1;
                 }
             }
         }
         return false;
    }

    int main()
    {
        init();
        if (!bfs())
            cout << "Impossible" ;

        char c;
        cin >> c;
        return 0;
    }

  • 相关阅读:
    从习总书记讲话学习表达
    Struts——(四)异常处理机制
    Struts框架——(三)动态ActionForm
    Struts框架——(二)Struts原理with登录实例
    Serializable接口和transient关键字
    转发(forward)和重定向(sendRedirect)
    Struts框架——(一)用Servlet + JSP演示Struts基本原理
    Cookie & Session
    Servlet
    SSH框架
  • 原文地址:https://www.cnblogs.com/icode-girl/p/4579040.html
Copyright © 2011-2022 走看看