Keep On Movin ~写题笔记

Problem Description

Professor Zhang has kinds of characters and the quantity of the i-th character is ai. Professor Zhang wants to use all the characters build several palindromic strings. He also wants to maximize the length of the shortest palindromic string.

For example, there are 4 kinds of characters denoted as 'a', 'b', 'c', 'd' and the quantity of each character is {2,3,2,2} . Professor Zhang can build {"acdbbbdca"}, {"abbba", "cddc"}, {"aca", "bbb", "dcd"}, or {"acdbdca", "bb"}. The first is the optimal solution where the length of the shortest palindromic string is 9.

Note that a string is called palindromic if it can be read the same way in either direction.

 

 

Input

There are multiple test cases. The first line of input contains an integer T, indicating the number of test cases. For each test case:

The first line contains an integer n (1≤n≤105) -- the number of kinds of characters. The second line contains n integers a1,a2,...,an (0≤ai≤104).

 

 

Output

For each test case, output an integer denoting the answer.

 

 

Sample Input

4
4
1 1 2 4
3
2 2 2
5
1 1 1 1 1
5
1 1 2 2 3

 

 

 

Sample Output

3
6
1
3

题目大意:数组a里有一些字符,第i个字符的数量是a[i],用这些字符来构造一些回文串,求各种组合方案中最短字符串长度的最大值,

举个栗子:

现在有 ‘a’, ‘b’, ‘c’, ‘d’ 四种字符并且他们的数量是 {2,3,2,2} 可以构造出 { “acdbbbdca”}, { “abbba”, “cddc”}, { “aca”, “bbb”, “dcd”},或{ “acdbdca”, “bb”} 四种方案.

在以上方案中,第一个方案的最短字符串长度比其他三种方案中的最短字符串长度都长,为9

 

解题思路:使每一种组合中的每一个字符串都尽可能的长 ,最后找出地最长的最短字符串才能是最长的 

举个例子:1 1 2 2 3     (a)  ( b) ( c c ) ( d d )  ( e e e ) 

(eee)为奇数个数,把它拆开,把拆开的(e)当作另一种字符 ,得到 (a)  (b) (e)   (c c) (d d) (e e),

 假设一个括号内代表一种字符
 使(a) (b)(c) 这三个个数为单的字符尽可能都得到其他字符的组合,使得他们的回文长度都尽可能变长(三个都尽可能变长,这样才能在所有方案中找到最长的那个) 

个数为单个的字符: (a)(b)(e)中总共有3个字符,记为cnt , cnt = 3 
个数为偶数的字符:(cc)(dd)(ee)中总共有6个字符,记为sum, sum = 6 
sum总为偶数,把sum个字符 加到 个数为单个的那些字符串上,使个数为单个 的字符串变长 
对于每一个个数为单个的字符 ,至少要加上 两个字符,才能使得它变成回文的 
所以把所有的偶数字符,两两分一组  得到group组( group= sum/2), 
看看平均每一个单个字符能分到多少组  (设能分到num 组, num = group / cnt)
组合后得到字符串的长度 : num * 2 + 1 
num * 2 是因为之前分过组了,每组里面有两个字符,求总字符个数的话就要乘以2
加1 是指还要加上 单个的字符这个字符 本身

#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdio>
using namespace std;
int main()
{
	int n, m;
	int t;
	cin >> t;
	while(t--)
	{
		cin >> n;
		int sum = 0; 
		int cnt = 0;
		for(int i = 1; i <= n; i++)
		{
			cin >> m;
			if(m % 2 == 0) 
				sum += m; 
			else //如果这种字符串的个数为奇数,把它拆开
			{
				sum += m - 1;
				cnt++;//单个字符的数目
			}
		}
		
		
		if(cnt == 0) cout << sum << endl;
		else 
		{
			int ans = sum / 2 / cnt * 2 + 1;
			cout << ans << endl;  
			
		}
	}
	
	return 0;
} 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值