#638 (Div. 2)A. Phoenix and Balance(找规律+递推)

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 n2 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.

题目大意:
有n个数,21 , 22 , 23…2n(n保证为偶数).将这n个数平均分成两组,求怎么分才能使这两组的差的绝对值最小。

题目分析:
分法很简单:将2n给第一组,2n-1一2n-n/2-1这n个数分给第二组,剩下的n-1个数再给第一组。
因为2到2n这n个数中,2n大于剩下n-1个数的和。因此,把2n分给一组后,一组的数就已经肯定大于二组了,所以把剩下数大的都给二组,小的都给一组即可。
由此我们可以发现:
n=2 时,答案是2.
n=4时,答案是6.
n=6时,答案是14.
n=12时,答案是30.
上一个数*2,再+2就可以得到下一个情况的答案。
这样我们就可以得到递推式了:f[i]=f[i-1]*2+2

代码如下:

#include <iostream>
#include <cstdio>
#include <cmath>
#include <string>
#include <cstring>
#include <map>
#include <queue>
#include <vector>
#include <algorithm>
#include <iomanip>
#define LL long long
using namespace std;
const int N=1e4+5;
int main()
{
	int t;
	cin>>t;
	while(t--)
	{
		int n;
		cin>>n;
		LL k=0;
		for(int i=2;i<=n;i+=2)   //n保证是偶数,所以每次+2
		k=k*2+2;            //通过递推式求出答案即可。
		 
		cout<<k<<endl; 
	}
    return 0;
}

猜你喜欢

转载自blog.csdn.net/li_wen_zhuo/article/details/105886331