先上题目:
Accept: 146 Submit: 319
Time Limit: 1000 mSec Memory Limit : 32768 KB
Problem Description
Yayamao is so cute that people loves it so much.
Everyone wants to buy Yayamao from Suneast (a business man who sells Yayamao).
Suneast is a strange business man. He sells Yayamao in a random price from 1, 2, 3, 4, 5…, n.
Suneast is also a lazy business man. He never looks for a change. But people can’t but Yayamao with a lower price, that say people must pay exact money for Yayamao.
Now, we want to know how many pieces of money people should bring with to buy a Yayamao with the exactly price.
Input
Output
Sample Input
Sample Output
Hint
In test case 1: people can bring 1 piece of money: 1
In test case 2: people can bring 2 pieces of money: (1, 1) or (1, 2)
In test case 3: people can bring 3 pieces of money: (1, 1, 3) or (1, 2, 2) ….
题意:给你一个数n,问你至少用多少个数,只用这些数就可以表示1~n的所有数。
比如5:1=1
2=1+1
3=1+2
4=2+2
5=1+1+3
当然可能还有很多的方法来表示1~5的数,不过一定需要三个。
其实我们可以这样分析,将这个数n化成二进制,假如它有l位,那么对于一个l位的二进制数,我们需要用l位二进制才可以将它表示出来,同时比它小的数,我们可以用不超过l位的数来保存表示它们,换言之,我们可以用2^0,2^1,2^2···2^k···这些数来表示从1~n的数,至于k等于多少,那就需要看n的二进制有多少位了。
这也是背包问题里面的多重背包的基础。
上代码:
1 #include <cstdio> 2 #include <cstring> 3 #define LL long long 4 #define MAX 2147483647 5 using namespace std; 6 7 8 int main() 9 { 10 int n; 11 int tot; 12 //freopen("data.txt","r",stdin); 13 while(scanf("%d",&n)!=EOF){ 14 tot=0; 15 while(n){ 16 tot++; 17 n=n>>1; 18 } 19 printf("%d ",tot); 20 } 21 return 0; 22 }