A. Phoenix and Balance

传送门

1348A. Phoenix and Balance

time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

题目描述
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个数,2^1 , 2 ^2 , 2 ^3…2 ^n(n保证为偶数).将这n个数平均分成两组,求怎么分才能使这两组的差的绝对值最小。

思路:解法一 :递推
n=2 时,答案是2.
n=4时,答案是6.
n=6时,答案是14.
n=12时,答案是30.
上一个数*2,再+2就可以得到下一个情况的答案。
这样我们就可以得到递推式了:a[i]=a[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 m;
	cin>>m;
	while(m--)
	{
		int n;
		cin>>n;
		LL sum=0;
		for(int i=2;i<=n;i+=2)   
		sum=sum*2+2;            
		cout<<sum<<endl; 
	}
    return 0;
}

解法二:找规律能发现结果为(2^(n/2+1))-2.
代码

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
	int m;
	scanf("%d", &m);
	while (m--)
	{
		int n;
		scanf("%d", &n);
		int p = pow(2, n / 2 + 1);
		printf("%d \n", p - 2);
	}
	return 0;
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

稚皓君

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值