加1乘2平方
描述:
最简单的队列
的使用
#include
#include
using namespace std;
queue q1;
int main()
{
int temp, x;
q1.push(5);//入队
q1.push(8);//入队
temp = q1.front();//访问队首元素
q1.pop();//出队
q1.empty();//判队列是否为空
q1.back();//返回队尾元素
q1.size();//返回队列长度
}
给定两个正整数m、n,问只能做加1、乘2和平方这三种变化,从m变化到n最少需要几次
输入:
输入两个10000以内的正整数m和n,且m小于n
输出:
输出从m变化到n的最少次数
输入样例:
1 16
输出样例:
3
源代码
#include <iostream>
#include <queue>
using namespace std;
int vis[10001];
int step[10001];
int m, n;
int make_new_place(int root,int type)
{
switch (type)
{
case 0:
return root + 1;
case 1:
return root * 2;
case 2:
return root * root;
}
return 0;
}
bool check(int num)
{
if(num > n || vis[num] != 0)
{
return false;
}
return true;
}
void bfs(queue<int> q,int m,int n)
{
int pop_num;
q.push(m);
while(!q.empty())
{
pop_num = q.front();
q.pop();
int new_num[3];
int i;
for (i = 0; i < 3; i++)
{
new_num[i] = make_new_place(pop_num, i);
if(check(new_num[i]))
{
q.push(new_num[i]);
step[new_num[i]] = step[pop_num] + 1;
vis[new_num[i]] = pop_num;
if(new_num[i] == n)
return;
}
}
}
}
int main()
{
cin >> m >> n;
queue<int> q;
bfs(q, m, n);
cout << step[n] << endl;
}
思路
这道题是广搜的第一道题,思路也比较简单。
- vis数组用于查重,从1到10000一万个元素,如果重复就记录为1,下次再查找1的时候就跳过。
- step数组用于记录步数当前结点产生的子结点步数加1。
- make_new_place为扩展结点,每次加1或者乘2或者平方。
- 每次出队的元素扩展三个新结点,这三个新结点不重复且不大于目标n的进队,直到队列为空。