ZZULIOJ 1427: 数字转换

来源:互联网 发布:苹果7下载软件 编辑:程序博客网 时间:2024/06/05 22:43

1427: 数字转换

Time Limit: 1 Sec  Memory Limit: 128 MB
Submit: 542  Solved: 144

SubmitStatusWeb Board

Description

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

Input

两个整数xy0<=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 0
原创粉丝点击