Professor Zhang has kinds of characters and the quantity of the ii-th character is aiai. 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}{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 nn (1≤n≤105)(1≤n≤105) – the number of kinds of characters. The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤104)(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
题意就是给你多种字母,和字母的个数,将其排列成回文字符串。
显然一组字母可以排列成好几个字符串,每一组里面有一个字符串的长度是最短的。让找出多组中哪一组的最短字符串的长度最长,并输出长度。
一开始看到题,总是想着,奇数个数的字母一定要在中间,然后相同的字母都放在一起。
后来才想明白,其实可以拆开的。这样就比较好做了。
因为奇数个数的字母一定是放在中间的,所以有几个奇数个数的字母,就有几个字符串。
但是,只需要在个数为奇数的字母中,取一个作为中间的字母。那么余下的就可以看作是偶数个的字母了。分配好中间字母以后,直接把偶数个的字母平均分给每个字符串就好了。
#include<iostream>
using namespace std;
int i, j, k, t;
int T, n;
int a[100005];
int m1, m2;
int main()
{
while (cin >> T)
{
for (i = 0; i < T; i++)
{
cin >> n;
memset(a, 0, sizeof(a));
for (j = 0, m1 = 0, m2 = 0; j < n; j++)
{
cin >> a[j];
if (a[j] % 2 == 1)//奇数
{
m1++;
if (a[j] > 1)
m2 += a[j] - 1;
}
else//偶数
m2 += a[j];
}
if (m1 > 0)
cout << 1 + ((m2 / 2) / m1) * 2 << endl;
else
cout << m2 << endl;
}
}
return 0;
}