【巧妙算法系列】【UVA 11384】 Help is needed for Dexter 正整数序列


Help is needed for Dexter

Time Limit: 3 Second

 

Dexter is tired of Dee Dee. So he decided to keep Dee Dee busy in a game. The game he planned for her is quite easy to play but not easy to win at least not for Dee Dee. But Dexter does not have time to spend on this silly task, so he wants your help.

 

There will be a button, when it will be pushed a random number N will be chosen by computer. Then on screen there will be numbers from 1 to N. Dee Dee can choose any number of numbers from the numbers on the screen, and then she will command computer to subtract a positive number chosen by her (not necessarily on screen) from the selected numbers. Her objective will be to make all the numbers 0.

 

For example if N = 3, then on screen there will be 3 numbers on screen: 1, 2, 3. Say she now selects 1 and 2. Commands to subtract 1, then the numbers on the screen will be: 0, 1, 3. Then she selects 1 and 3 and commands to subtract 1. Now the numbers are 0, 0, 2. Now she subtracts 2 from 2 and all the numbers become 0.

 

Dexter is not so dumb to understand that this can be done very easily, so to make a twist he will give a limit L for each N and surely L will be as minimum as possible so that it is still possible to win within L moves. But Dexter does not have time to think how to determine L for each N, so he asks you to write a code which will take N as input and give L as output.

 

Input and Output:

Input consists of several lines each with N such that 1 ≤ N ≤ 1,000,000,000. Input will be terminated by end of file. For each N output L in separate lines.

 

SAMPLE INPUT

OUTPUT FOR SAMPLE INPUT

1

2

3

1

2

2

 

思路:

很容易发现


切掉一块后 再切掉的两边形成两个子问题

将接下来的两个子问题解决的步数  取决于值较大哪一方


显然 因此我们若切一刀 使两个子问题平均点的话 无疑是最优方案




书上答案:

拿到这道题目之后,最好的方式是自己试一试。经过若干次尝试和总结后,不难发现第一步的最好方式



换句话说,当n=6的时候留下1, 2, 3,而把4,5,6同时减去min{4,5,6}=4得到序列1, 2, 3, 0, 1, 2,它等价于1, 2, 3(想一想,为什么)。换句话说,f(6)=f(3)+1。

一般地,为了平衡,我们保留1~n/2,把剩下的数同时减去n/2+1,得到序列1, 2, …,n/2, 0,1,…,(n-1)/2,它等价于1, 2, …,n/2,因此f(n)=f(n/2)+1。边界是f(1)=1。


代码:

#include<stdio.h>
int getans(int n)
{
	if(n==0) return 0;
	if(n==1) return 1;
	else return getans(n>>1)+1;
}
int main()
{
	int n;
	while(scanf("%d",&n)!=EOF)
	{
		printf("%d\n",getans(n));
	}
	return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值