Problem Description
Recently, Peter saw the equation x0+2x1+4x2+...+2mxm=n. He wants to find a solution (x0,x1,x2,...,xm) in such a manner that ∑i=0mxi is minimum and every xi (0≤i≤m) is non-negative.
Input
There are multiple test cases. The first line of input contains an integer T (1≤T≤105), indicating the number of test cases. For each test case:
The first contains two integers n and m (0≤n,m≤109).
The first contains two integers n and m (0≤n,m≤109).
Output
For each test case, output the minimum value of ∑i=0mxi.
Sample Input
10 1 2 3 2 5 2 10 2 10 3 10 4 13 5 20 4 11 11 12 3
Sample Output
1 2 2 3 2 2 3 2 3 2
题目大意:给定n,m;求使2^0*x1+2^1*x2+…+2^m=n成立的x1-xn相加和的最小值。
思路:
由于我们的目的是使得x1-xn的值最小;我们可以让系数最大的第m项的值最大来最大程度地减小答案,当m项解决后再考虑m-1项,以此类推,直到n被完全表示 ,最后把所有x统计一下即可。
最后附上代码。
1 #include<cstdio> 2 #include<cmath> 3 #include<cstring> 4 #include<algorithm> 5 using namespace std; 6 const int N=5e3+10; 7 int n,m,t; 8 long long sum; 9 int main(){ 10 scanf("%d",&t); 11 while(t--){ 12 scanf("%d%d",&n,&m); 13 sum=0; 14 m=min(m,32); 15 for(int i=m;i>=0;--i){ 16 long long cnt=(long long)pow(2,i); 17 sum+=(n/cnt); 18 if(n%cnt==0) break; 19 n%=cnt; 20 } 21 printf("%d ",sum); 22 } 23 return 0; 24 }