Problem A
加1乘2平方
时限:1000ms 内存限制:10000K 总时限:3000ms
描述:
最简单的队列的使用
#include <iostream>
#include <queue>
using namespace std;
queue<int> 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;
queue<int>q;
int m,n; int used[10001]={0};//记录已经搜索果的数,0表示未用过1表示已用过 int step[10001]={0};//记录步数 ,不能用简单的count计数
int bfs(); int canplace(int a,int b);
int main() { int ans; cin>>m>>n; ans=bfs(); cout<<ans<<endl; }
int bfs() { q.push(m);//入队 used[m]=1; while(!q.empty()) //当队列不为空时 { int i,v,u; u=q.front();//访问队首元素 q.pop();//出队 for(i=0;i<3;i++)//0表示加1,1表示乘2,2表示平方 { v=canplace(u,i); if(v==n) { step[u]++; return(step[u]); } if(v<n&&used[v]==0) { q.push(v); used[v]=1; step[v]=step[u]+1; } } } q.back();//返回队尾元素 q.size();//返回队列长度 }
int canplace(int a,int b) { if(b==0) return(a+1); if(b==1) return(2*a); if(b==2) return(a*a); }