hdu 5587 (Array)

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

3
1
3
5

Sample Output

1
4
7

题意:刚开始集合里面只有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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值