2017年上海金马五校程序设计竞赛(网上资格赛) Problem J : Raising Bacteria

本文介绍了一种通过计算细菌繁殖的数学模型来解决特定问题的方法。该问题要求找到最少需要放置多少细菌才能在某一天达到指定数量。通过预先计算2的幂次并使用贪心算法递减匹配目标值,实现了高效求解。

Description

You are a lover of bacteria so you want to raise some bacteria in a box. Initially, the box is empty. Every morning, you can put any number of bacteria into the box. Every night every bacterium in the box will split into two bacteria. You hope to see exactly xx bacteria in the box at some moment. What is the minimum number of bacteria you need to put into the box across those days?

 

Input

There are several test cases. Each case contains only one integer xx (1x109)(1≤x≤109) a line.

 

Output

For each case, output the only line containing one integer: the answer.

 

Sample Input

5
8

 

Sample Output

2
1

我是预估10^9的2的n次方大概在30,然后把他们算出来存到数组里,把给出的数找他最接近的那个减掉,在找最近的减掉,每次减掉加一个细胞就可以了


#include <iostream>
#include <cstring>
#include <cstdio>
#include <math.h>
using namespace std;
int X[30];
int main()
{
	for(int i=0;i<30;i++)
	{
		X[i]=pow(2,i);
		
	}
	int n;
	while(scanf("%d",&n)!=EOF)
	{
		int count=0;
		for(int i=29;i>=0;i--)
		{
			if(n-X[i]>=0)
			{
				n-=X[i];
				count++;
				if(n<=0) break;
			 }  
		}
		printf("%d\n",count);
	}
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

_我走路带风

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值