HDU 5587 递推 规律

24 篇文章 0 订阅
20 篇文章 0 订阅

http://acm.hdu.edu.cn/showproblem.php?pid=5587

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.(1≤T≤2∗103)(1≤T≤2∗103)
Next T line contains, each line contains one interger M. (1≤M≤1016)(1≤M≤1016)

Output

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

Sample Input

3
1
3
5

Sample Output

1
4
7

题目大意:第n+1天把第n天的数组的全部元素复制到末尾,中间以0间隔,同时把今天新增的数(包括0)都加上1。解释一下样例:n=1时,{1};n=2时,{1,1,2};n=3时,{1,1,2,1,2,2,3}。然后求第100天的时候数组前m个元素之和。

思路:比赛时候果然智商下降,这个推半天都推不利索orz。我们举一个n=4时候的例子,这时候数组为{1,1,2,1,2,2,3,1,2,2,3,2,3,3,4}。然后我们观察一下第1个元素,前2个元素,前4个元素,前8个元素分别为:

i=0第一个1      
i=1前两个11     
i=2前四个1121   
i=3前八个1121223

会发现后半部分和前半部分是一一对应的,因为就是复制过来的,只不过加了1而已,注意最后一个元素并没有变化。如果我们用f[i]表示数组前2^i个元素的和,那么可以得到递推公式:f[0]=1,f[i]=2*f[i-1]+2^(i-1)-1。那么如何计算100天之和前m个元素的和呢?我们找到不大于m的以2为底的指数。假设是k,那么有m>=2^k,分两种情况来看:(1)m=2^k,那么结果显然是f[k]。(2)m>2^k,首先前2^k个元素的和为f[k],然后还有从2^k+1到m的元素,还记得我们上面提到的对应关系吗?从2^k+1到m的元素之和其实就等于f[m-2^k]+m-2^k。(因为后半部分的元素都增加了1)有了(1)、(2)的分析,我们就可以计算前m个元素的值了,用递归,用循环都可以。

#include<iostream>
#include<cstdio>
#include<stack>
#include<cmath>
#include<cstring>
#include<queue>
#include<set>
#include<algorithm>
#include<iterator>
#define INF 0x3f3f3f3f
typedef long long ll;
typedef unsigned long long ull;
using namespace std;

ll m2[70];
ll f[105];

void solve(ll m);

int main()
{
	m2[0]=1;
	m2[1]=2;
	for(int i=2;i<=62;i++)
		m2[i]=m2[i-1]*2;	//2^n
	f[0]=1;
	for(int i=1;i<=58;i++)
	{
		f[i]=2*f[i-1]+m2[i-1]-1;
	}
	int t;
	while(~scanf("%d",&t))
	{
		while(t--)
		{
			ull m;
			scanf("%lld",&m);
			solve(m);
		}
	}
	return 0;
}

void solve(ll m)
{
	ll i=0;
	ll temp;
	ll sum=0;
	while(1)
	{
		if(m==0)
			break;
		else if(m==1)
		{
			sum+=1;
			break;
		}
		i=0;
		temp=0;
		ll t=m;
		while(t>1)
		{
			t/=2;
			++i;
		}
		temp=pow(2,i);
		if(m==temp)
		{
			sum+=f[i];
			break;
		}
		else
			sum+=f[i]+m-temp;
		m=m-temp;
	}
	printf("%llu\n",sum);
}

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值