Phoenix has n coins with weights 21,22,…,2n. He knows that n is even.He wants to split the coins into two piles such that each pile has exactly n/2 coins and the difference of weights between the two piles is minimized. Formally, let a denote the sum of weights in the first pile, and b denote the sum of weights in the second pile. Help Phoenix minimize |a−b|, the absolute value of a−b.
Input
The input consists of multiple test cases.
The first line contains an integer t (1≤t≤100) — the number of test cases.
The first line of each test case contains an integer n (2≤n≤30; n is even) — the number of coins that Phoenix has.
Output
For each test case, output one integer — the minimum possible difference of weights between the two piles.
Example
input
2
2
4
output
2
6
Note
In the first test case, Phoenix has two coins with weights 2 and 4. No matter how he divides the coins, the difference will be 4−2=2.
In the second test case, Phoenix has four coins of weight 2, 4, 8, and 16. It is optimal for Phoenix to place coins with weights 2 and 16 in one pile, and coins with weights 4 and 8 in another pile. The difference is (2+16)−(4+8)=6.
一开始没使用函数,不知道为什么会出错,求高人指点。
#include<iostream>
#include<cmath>
using namespace std;
int bal(int n)
{
int s1,s2=0;
for(int i=1;i<n/2;i++)
{
s1=s1+pow(2,i);
}
s1=s1+pow(2,n);
for(int j=n/2;j<n;j++)
{
s2=s2+pow(2,j);
}
cout<<fabs(s1-s2)-n<<endl;
}
int main()
{
int t=0;
cin>>t;
while(t--)
{
int n;
cin>>n;
bal(n);
}
}
本文探讨了一个算法问题,即如何将一组按2的幂次规律排列的硬币分为两堆,使得每堆硬币的数量相等且两堆之间的重量差最小。通过示例说明了最优解的寻找过程,并提供了一段C++代码实现,但该代码存在问题,有待高手指导优化。
905

被折叠的 条评论
为什么被折叠?



