【Codeforces 600C. Make Palindrome】& 构造

C. Make Palindrome
time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
A string is called palindrome if it reads the same from left to right and from right to left. For example “kazak”, “oo”, “r” and “mikhailrubinchikkihcniburliahkim” are palindroms, but strings “abb” and “ij” are not.

You are given string s consisting of lowercase Latin letters. At once you can choose any position in the string and change letter in that position to any other lowercase letter. So after each changing the length of the string doesn’t change. At first you can change some letters in s. Then you can permute the order of letters as you want. Permutation doesn’t count as changes.

You should obtain palindrome with the minimal number of changes. If there are several ways to do that you should get the lexicographically (alphabetically) smallest palindrome. So firstly you should minimize the number of changes and then minimize the palindrome lexicographically.

Input
The only line contains string s (1 ≤ |s| ≤ 2·105) consisting of only lowercase Latin letters.

Output
Print the lexicographically smallest palindrome that can be obtained with the minimal number of changes.

Examples
input
aabc
output
abba
input
aabcd
output
abcba

题意 : 给出一串字符串,每次可以选取一个字符把它变成其他字符,可以交换字符的位置,构成字典序最小的回文串,且改变的字符次数最少

思路 : 字符个数要么为奇数,要么为偶数,偶数的不用变,奇数的都要变,且变一半就好,又因为字典序最小,自然把大的一半,变成小的一半

AC代码:

#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
using namespace std;
const int MAX = 2e5 + 10;
typedef long long LL;
char s[MAX];
int n[26];
int main()
{
    scanf("%s",s);
    int nl = strlen(s);
    for(int i = 0; i < nl; i++) n[s[i] - 'a']++;
    int l = 0,r = 25;
    while(1){
        while(n[r] % 2 == 0) r--;
        while(n[l] % 2 == 0) l++;
        if(l >= r) break;
        n[r]--,n[l]++;
    }
    l = 0;
    for(int i = 0,j = nl - 1; i < j; i++,j--){
        while(n[l] < 2) l++;
        n[l] -= 2;
        s[i] = s[j] = l + 'a';
    }
    if(nl & 1){
        l = 0; while(!n[l]) l++;
        s[nl / 2] = l + 'a';
    }
    printf("%s\n",s);
    return 0;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值