hdu 5587 (Array)

来源:互联网 发布:淘宝卖家企业店铺 编辑:程序博客网 时间:2024/06/15 04:22

Array

Description

Vicky is a magician who loves math. She has great power in copying and creating. 
One day she gets an array {1}。 After that, every day she copies all the numbers in the arrays she has, and puts them into the tail of the array, with a signle '0' to separat. 
Vicky wants to make difference. So every number which is made today (include the 0) will be plused by one. 
Vicky wonders after 100 days, what is the sum of the first M numbers.

Input

There are multiple test cases. 
First line contains a single integer T, means the number of test cases. 
Next T line contains, each line contains one interger M. 

Output

For each test case,output the answer in a line. 

Sample Input

3135

Sample Output

147

题意:刚开始集合里面只有1,每天复制之前的数,并将新增的数加1(包括0),前一天的数与新增的数之间用0间隔开,问100天后前M个数的和。 第一天:{ 1 }    第二天:{ 101 } --> { 112 }    第三天:{ 112 0 112 } --> { 1121223 }  第四天:{ 1121223 0 1121223 } --> { 1121223 12232334 }    所以前3项的和为 1+1+2=4   前5项的和为 1+1+2+1+2=7.

题解: 可以知道前n天的序列的个数 num[ n ]=num[n-1]*2+1 ( 复制了前n-1天的数字,又加了0 )   前n天序列的和为 

sum[ n] =2*sum[n-1] +num[n-1]+1  ( 复制前n-1 天的和,同时新增的 num[n-1] 个数+1,还有0也加1).

找出x天后序列长度恰好为m,如果不是,则递归找出剩下的序列。

#include<cstdio>#include<cstring>#include<algorithm>using namespace std;long long num[110];long long sum[110];void init(){int i;memset (num,0,sizeof(num));memset (sum,0,sizeof(sum));num[1]=1,sum[1]=1;for (i=2;i<66;i++){num[i]=num[i-1]*2+1;sum[i]=2*sum[i-1]+num[i-1]+1;}}long long solve(long long x){if (x<=1) return x;int ans=lower_bound(num,num+65,x)-num;//找到第ans天的长度大于等于x if (num[ans]==x) return sum[ans]; return sum[ans-1]+solve(x-num[ans-1]-1)+x-num[ans-1];//solve(x-前一天的长度-'0') }int main(){int t;long long m;scanf ("%d",&t);while (t--){scanf ("%lld",&m);init();printf ("%lld\n",solve(m));}return 0;} 

还可以用二分,位运算的方法

0 0