【Codeforces 600C. Make Palindrome】& 构造

来源:互联网 发布:js怎么获取input的值 编辑:程序博客网 时间:2024/05/16 00:40

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;}
原创粉丝点击