Keep On Movin
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 1040 Accepted Submission(s): 733
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
Author
zimpha
Source
2016 Multi-University Training Contest 2
题意:
有n个字符,每个字符的数目是ai个。现在我们要全部用上这些字符把他们组成多组回文数,问你在这多组回文数中最短的串的最大长度为多少?
例如:a,a,b,b 可以组成
a ; a ;b ; b ;
aa ; bb;
abba;
….
等很多组,最短的最长长度为4:abba
分析:
因为所有的字符自身不管有多少个都可以组成回文数。而偶数数目的一定最后可以加在其他的两端使最小的长度增大。
所以我们可以将这些字符分为偶数数目的,和奇数数目的。
而对于奇数数目ai的我们又可以将他们看成1+ai-1,1加上一个偶数
所以最后就变成了多个1和多个偶数的集合了
为了使最短的最大所以我们平均分配(每两个一组放在两端)给每个1即可
AC代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
const int maxn = 100010;
int a[maxn],b[maxn];
int numa,numb;
int main()
{
int t,n,x,ans;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
ans = numa = numb = 0;
for(int i=0;i<n;i++)
{
scanf("%d",&x);
if(x&1) a[numa++] = x;
else b[numb++] = x;
}
if(numa == 0) //全为偶数
{
for(int i=0;i<numb;i++) ans += b[i];
printf("%d\n",ans);
}
else
{
int t = 0;//可分为t个2
for(int i=0;i<numa;i++) t += a[i]/2;
for(int i=0;i<numb;i++) t += b[i]/2;
t = t/numa; //平均分配数
ans = 1 + t*2;
printf("%d\n",ans);
}
}
return 0;
}