1.以下代码运用了哪种算法?
2.是如何实现运行的?
3.如何进行改进?
#include
#include
#include
#include
static int big_max_value[] =
{
8, 5, 8
};
static int small_max_value[] =
{
5, 3, 3
};
static const int big_offset[] =
{
0, 1, 0
};
static const int small_offset[] =
{
1, 2, 2
};
//节点定义
class Node
{
unsigned char mBig;
unsigned char mMid;
unsigned char mSmall;
public:
static void InitMax Value(int max1, int max2, int max3)
{
big_max_value[0] = max1;
big_max_value[1] = max2;
big_max_value[2] = max1;
small_max_value[0] = max2;
small_max_value[1] = max3;
small_max_value[2] = max3;
}
Node() : mBig(0), mMid(0), mSmall(0)
{
}
Node(unsigned char a, unsigned char b, unsigned char c) : mBig(a), mMid(b), mSmall(c)
{
}
enum OPCODE
{
BIG_OP_MIDDLE = 0,
MIDDLE_OP_SMALL,
BIG_OP_SMALL,
OP_LAST
};
//减运算
void sub(OPCODE op)
{
int big_max = big_max_value[op];
int small_max = small_max_value[op];
char& big = *(reinterpret_cast<char*>(this) + big_offset[op]);
char& small = *(reinterpret_cast<char*>(this) + small_offset[op]);
if (big > (small_max - small))
{
big -= (small_max - small);
small = small_max;
}
else
{
small += big;
big = 0;
}
}
//加运算
void add(OPCODE op)
{
int big_max = big_max_value[op];
int small_max = small_max_value[op];
char& big = *(reinterpret_cast<char*>(this) + big_offset[op]);
char& small = *(reinterpret_cast<char*>(this) + small_offset[op]);
if (small > big_max - big)
{
small -= big_max - big;
big = big_max;
}
else
{
big += small;
small = 0;
}
}
bool check(int value)
{
if (mBig == value || mMid == value || mSmall == value)
{
return true;
}
return false;
}
void print() const
{
printf("[%d]=%2d,[%d]=%2d,[%d]=%2d \n ", big_max_value[0], mBig, big_max_value[1], mMid,small_max_value[2], mSmall);
}
//相等性判定
friend bool operator==(Node const & a, Node const & b)
{
return memcmp(&a, &b, sizeof(Node)) == 0;
}
friend bool operator <(Node const & a, Node const & b)
{
return memcmp(&a, &b, sizeof(Node)) < 0;
}
};
template <class T>
void Search(T start, int value)
{
typedef std::pair NodeValueType;
typedef std::map NodeSet;
typedef NodeSet::iterator NodeSetIter;
typedef std::queue > NodeQueue;
NodeSet visited;
NodeQueue searchQueue;
NodeValueType last;
searchQueue.push(std::make_pair(start, start));
while (!searchQueue.empty())
{
NodeValueType cur = searchQueue.front();
searchQueue.pop();
visited.insert(cur);
if (cur.first.check(value))
{
last = cur;
break;
}
for (int i = 0; i < Node::OP_LAST; i++)
{
Node next1 = cur.first;
next1.sub(static_cast(i));
if (visited.find(next1) == visited.end())
{
searchQueue.push(std::make_pair(next1, cur.first));
}
Node next2 = cur.first;
next2.add(static_cast(i));
if (visited.find(next2) == visited.end())
{
searchQueue.push(std::make_pair(next2, cur.first));
}
}
}
NodeSetIter cur = visited.find(last.first);
while (!(cur->first == start))
{
cur->first.print();
cur = visited.find(cur->second);
}
cur->first.print();
}
int main()
{
puts(" [8]= 4,[5]= 4,[3]= 0");
{
printf("查找取得(4,4,0)的最少步骤,逆序 \n ", (4,4,0));
Search(Node(8, 0, 0), 4);
}
return 0;
}