整数变换问题
No Solution
#include "stdafx.h" #include<vector> #include<iostream> using namespace std; typedef unsigned char byte; struct Node { vector<byte>path; int current_value; }; Node solution; vector<Node>nextnodelist; bool integer_trans(int m, int n, vector<Node>nodelist) { if (nodelist[0].path.size() == 25) { cout << "已达到最大层数,未找到" << endl; return true; } nextnodelist.clear(); cout << nextnodelist.size() << endl; int k = 0; while (k < nodelist.size()) { if (nodelist[k].current_value % 3 == 0) { Node node; node.path = nodelist[k].path; node.path.push_back(0); node.current_value = nodelist[k].current_value / 3; nextnodelist.push_back(node); if (node.current_value == n) { solution = node; return true; } } Node node1; node1.path = nodelist[k].path; node1.path.push_back(1); node1.current_value = nodelist[k].current_value * 2; nextnodelist.push_back(node1); if (node1.current_value == n) { solution = node1; return true; } Node node2; node2.path = nodelist[k].path; node2.path.push_back(2); node2.current_value = nodelist[k].current_value * 2+1; nextnodelist.push_back(node2); if (node2.current_value == n) { solution = node2; return true; } k++; } return false; } void solve(int m, int n) { Node nn; nn.current_value = m; nextnodelist.push_back(nn); bool flag = false; while (!flag) { vector<Node>nodelist(nextnodelist); flag = integer_trans(m, n, nodelist); } } int _tmain(int argc, _TCHAR* argv[]) { solve(4, 15); system("pause"); return 0; }
每个node存储它之前操作的记录,0代表f,即/3,1代表*2,2代表*2+1,value存储当前值。nodelist只存储一层的节点即可。
因为每次对f先进行操作,也先进行存储,所以找到的第一个满足要求的解也是字典序最小的,直接返回即可。
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/u014568921/article/details/46941463