I — 求和(贪心)

1.PNG

 2.PNG

 3.PNG

Sample Input 1

5
10 4
13 5
20 4
11 11
12 3

Sample Output 1

2
3
2
3
2

解析:此题中的m虽然范围是0~1e9,但是n最大为1e9,所以m最大是30,因为2的30次方就已经大于1e9了,所以可以从m=30开始遍历,再用贪心的思想去做就可以了;

#include<iostream>
using namespace std;
typedef long long ll;
ll a[35];
int main()
{
	int t;
	scanf("%d",&t);
	a[0]=1;
	for(int i=1;i<31;i++){
		a[i]=a[i-1]*2;
	}
	while(t--){
		ll n,m;
		scanf("%lld%lld",&n,&m);
		if(m>30) m=30;
		ll sum=0;
		for(int i=m;i>=0;i--){
			if(a[i]<=n){
				sum+=n/a[i];
				n=n%a[i];
				if(n==0) {
					break;
				}
			}
		}
		printf("%lld\n",sum);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41555192/article/details/82152599
I