HDOJ 5744 Keep On Movin(回文串)

本文探讨了如何利用给定的字符集构建多个回文字符串,并最大化最短回文串的长度。通过分析字符数量及奇偶性,提出了有效的算法解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Keep On Movin

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 791    Accepted Submission(s): 572


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 (1n105) -- the number of kinds of characters. The second line contains n integers a1,a2,...,an (0ai104) .
 

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



思路:
题意就是说,给定你几个字母,让你看看他们能不能构成n个回文串,并且找每个回文串组中的长度最小值,然后再在这些最小值中找最大值。这就是对字母个数分组,如果字母都是偶数个,那很好,能平分成两个长度等长的。如果有字母的个数为奇数,那么先把这个1拿出来,剩下的还是能均等分成两份,再把这个1加到其中一个的中间位置。如果有n个奇数,那么先把n个1先拿出来,再剩下的均分成n份,再加进去1。

代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;

const int N=100010;
int a[N],b[N];

int main()
{
    int T,n;
    scanf("%d",&T);
    while (T--)
    {
        scanf("%d",&n);
        int x,odd=0,sum=0;
        for (int i=1;i<=n;i++)
        {
            scanf("%d",&x);
            if (x&1) odd++,sum+=x-1;
            else sum+=x;
        }
        if (odd==0) printf("%d\n",sum);
        else printf("%d\n",sum/odd/2*2+1);
    }
    return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值