0
点赞
收藏
分享

微信扫一扫

ZZULIOJ 1427: 数字转换



1427: 数字转换


Time Limit: 1 Sec   Memory Limit: 128 MB

Submit: 542  

Solved: 144


​​Submit​​

​​Status​​

​​Web Board​​


Description


老师交给小明一个任务,有两个数字x和y(x<y),通过以下两种操作:一、将x乘以2;二、将x的值加上1。小明希望能通过尽可能少的操作来完成这个任务,但是不知道怎么做,现在请大家来帮帮他的忙吧。


Input


两个整数x,y(0<=x<y<=10^6)。


Output


一个整数n,表示最少经过多少次操作,x可以变成y。


Sample Input


2 5



10 80


Sample Output


2



3


HINT



Source


​​郑轻第六届校赛​​




数学,,思维耶-.-队列TLE。。。百度了题解反推过。。。

TLE代码:

#include<cstdio>
#include<cstring>
#include<queue>
#include<algorithm>
using namespace std;
struct node{
int x,step;
}now,qian;
void zhao(int xx,int yy)
{
queue<node> que;
now.step=0;now.x=xx;
que.push(now);
while (!que.empty())
{
qian=que.front();
que.pop();
if (qian.x==yy)
{
printf("%d\n",qian.step);
break;
}
now.x=qian.x*2;now.step=qian.step+1;
if (now.x<=yy) que.push(now);
now.x=qian.x+1;now.step=qian.step+1;
if (now.x<=yy) que.push(now);
}
}
int main()
{
int x,y;
while (scanf("%d%d",&x,&y)!=EOF)
zhao(x,y);
return 0;
}


AC 代码:

#include<stdio.h>
int main()
{
int x,y;
while(~scanf("%d%d",&x,&y))
{
int k=0;
while(y>x)
{
if(y%2==1)
y-=1;
else
y/=2;
k++;
}
if(y<x)
k+=2*y-x-1;
printf("%d\n",k);
}
}



举报

相关推荐

0 条评论