CODEFORCES:B. Two Buttons
来源:互联网 发布:老时时彩计划软件 编辑:程序博客网 时间:2024/05/28 05:18
Vasya has found a strange device. On the front panel of a device there are: a red button, a blue button and a display showing some positive integer. After clicking the red button, device multiplies the displayed number by two. After clicking the blue button, device subtracts one from the number on the display. If at some point the number stops being positive, the device breaks down. The display can show arbitrarily large numbers. Initially, the display shows numbern.
Bob wants to get number m on the display. What minimum number of clicks he has to make in order to achieve this result?
The first and the only line of the input contains two distinct integers n and m (1 ≤ n, m ≤ 104), separated by a space .
Print a single number — the minimum number of times one needs to push the button required to get the numberm out of number n.
4 6
2
10 1
9
In the first example you need to push the blue button once, and then push the red button once.
In the second example, doubling the number is unnecessary, so we need to push the blue button nine times.
题目还是很容易看懂的:给你两个按钮red和blue,输入n和m,要求n变到m最少需要几步。一个按钮可以进行减一的操作,另一个按钮可以将n乘以2的操作。这样可以想一下,当n<<m的时候,我可以希望n能够变到m*1/2的状态,然后只要一步操作就够了。以此类推,n变到m的1/4,1/8……这样的操作数可以达到最少。所以先在进行递归判断之前进行上述的处理,就可以出来了。
#include<stdio.h>
#include<math.h>
int t,f;
void buttons(int n,int m,int cnt)
{
// printf("%d ",n);
if(f)return;
t=cnt;
if(n==m){f=1;return;}
if(n*2<=m)buttons(n*2,m,cnt+1);
if(n*2>m){
if(fabs(n*2-m)<=fabs((n-1)*2-m))buttons(n*2,m,cnt+1);
else buttons(n-1,m,cnt+1);
}
}
int main()
{
int n,m,i,j;
while(scanf("%d%d",&n,&m)!=EOF)
{
f=0;
t=0;
if(m<=n)t=n-m;
else
{
while(n*2<m)
{if(m%2==1){m=m/2+1;t=t+2;}
else {m=m/2;t=t+1; }
}// printf("m=%d ",m);
buttons(n,m,t);
}
printf("%d\n",t);
}
return 0;
}
- CODEFORCES:B. Two Buttons
- CodeForces 520B【Two Buttons】
- Codeforces 520B. Two Buttons
- Codeforces 520B.Two Buttons
- B. Two Buttons(Codeforces Round #295(div2))
- Codeforces Round #295 B. Two Buttons
- Codeforces 520B. Two Buttons spfa
- Codeforces 520 B Two Buttons BFS
- Codeforces 520B Two Buttons 【BFS】||【spfa】
- Codeforces 295 Div2 B.Two Buttons
- codeforces 520B Two Buttons BFS
- Codeforces 520B Two Buttons 题解
- CodeForces 520 B.Two Buttons(bfs)
- B. Two Buttons
- B. Two Buttons
- Codeforces Round #295 (Div. 2) -- B. Two Buttons (模拟)
- codeforces 520B Two Buttons[记忆化搜索]
- CodeForces 520B Two Buttons bfs+优先队列
- awk转置文本
- Quick Sort 快速排序的原理及实现
- [LeetCode]Validate Binary Search Tree
- Unity3D 移动MM 支付SDK 问题
- Android Studio导入第三方类库的方法
- CODEFORCES:B. Two Buttons
- eRevit Surfacer简介
- 黄金圆圈
- 如何判断自动化测试架构的好与坏
- 通过 JMX 获取Hadoop/HBase监控数据
- 工业总产值
- 多线程
- 数据分析算法----1决策树
- 电信141p51第19题