Keep On Movin
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 232 Accepted Submission(s): 174
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.
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) .
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
题解:我看这题目就看了一个小时,我语文不好,这题目实在是有点表意不明,有点绕的我都晕了。其实后来,写不出来,看了题解,恍然大悟,有一种日了dog的感觉,分两种情况,全偶数,和有奇数,对于有奇数,不就是相当于求求平均数吗。。。
代码如下:
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int main()
{
long long sum,T,k,l,a[100005],t,n,i;
scanf("%lld",&T);
while(T--)
{
scanf("%lld",&n);
sum=0;
for(i=0,k=0,l=0;i<n;i++)
{
scanf("%lld",&t);
sum+=t;
if(t%2==1)
a[k++]=t;
}
if(k==0)
{
printf("%lld\n",sum);
}
else
{
t=sum/k;
if(t%2==0)
t--;
printf("%lld\n",t);
}
}
return 0;
}
因为我是看了题解才写出来的,这里一定要再理清下自己的思路。这道题一开始可以很晕地推出,奇数有多少个,最少的字符串就有多少个。偶数的话,单独能存活下来,加进去奇数里面也能存活下来。再回到奇数这,奇数有多少个,其实直接简化成都是1,比如是1 3 5 7,就简化成1 1 1 1,多出来的2 4 6在我一开始读入的时候,全部数字我都加进了sum里面,我就不管了。既然都是1 1 1 1,sum里面包含一开始的奇数和偶数之和,我就直接用sum去除以这个奇数的个数就行了,这就相当于求平均数了。但是又有一个问题,1和N个2组合起来回文串,最终的字符串肯定是奇数,如果我们算出的这个平均数是个偶数,是不符合规范的,这时我们的做法是平均数减1再输出,为什么要减去1呢?这就相当于平均数是4,奇数个数是2,也就是第一个样例,我们对平均数减去1,就相当于有一个组能+1,变成了3和5,符合要求。3就是我们要输出的,肯定是最大的了。因为已经是最接近平均数的答案了。