CF1840B

题目描述

Once upon a time, Toma found himself in a binary cafe. It is a very popular and unusual place.

The cafe offers visitors kk different delicious desserts. The desserts are numbered from 0to k−1 . The cost of the i -th dessert is 2^i coins, because it is a binary cafe! Toma is willing to spend no more than nn coins on tasting desserts. At the same time, he is not interested in buying any dessert more than once, because one is enough to evaluate the taste.

In how many different ways can he buy several desserts (possibly zero) for tasting?

输入格式

The first line of the input contains a single integer t ( 1≤t≤1000 ) — the number of test cases.

Then follows t lines, each of which describes one test case.

Each test case is given on a single line and consists of two integers n and k ( 1≤n,k≤10^9) — the number of coins Toma is willing to spend and the number of desserts in the binary cafe.

输出格式

Output t integers, the i-th of which should be equal to the answer for the i-th test case — the number of ways to buy desserts for tasting.

输入样例

5
1 2
2 1
2 2
10 2
179 100

输出样例

2
2
3
4
180

说明/提示

Variants for 1st sample: {}, {1}
Variants for 2nd sample: {}, {1}
Variants for 3rd sample: {}, {1}, {2}
Variants for 4th sample: {}, {1}, {2}, {1, 2}

分析

甜品的编号是从0开始的,所以第0号甜品花费的硬币为1硬币,第1个甜品为2个硬币,第2个甜品为4个硬币,
所以如果有n个甜品全部都尝试花费总的硬币数为2^n-1,三个甜品总共花费的硬币为7个,正好是2的3次方-1,这就是二进制的一个特性,2的n次方-1,就等于2的0次方+2的1次方…+2的n-1次方。

如果硬币的数量大于2^k-1,那就说明所有的尝甜品的方式都能满足,如果小于等于2的k次方-1,只能尝试n种方式。从1到n转化成2进制数,位置上是1的尝试,是0的不尝试,总共n种尝试方式。

#include<bits/stdc++.h>
using namespace std;
int main()
{
	long long t,n,k,tmp;
	cin>>t;
	while(t--)
	{
		cin>>n>>k;
		
		if(k>=30||n<=pow(2,k)-1)
			cout<<n+1<<endl;
		else
			cout<<(int)pow(2,k)<<endl;//pow(2,k)前面如果不加int就会报错,在计算的过程中结果越界。	
	}
	return 0;	
 } 

如果使用(1<<k)代替pow(2,k) ,就不会存在这个问题了,它是移位的方式不存在越界

#include<bits/stdc++.h>
using namespace std;
int main()
{
	long long t,n,k,tmp;
	cin>>t;
	while(t--)
	{
		cin>>n>>k;
		
		if(k>=30||n<=(1<<k)-1)//使用(1<<k)代替pow(2,k) 
			cout<<n+1<<endl;
		else
			cout<<(1<<k)<<endl;	//pow(2,k)前面如果不加int就会报错? 
	}
	return 0;	
 } 
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值