CodeForces

来源:互联网 发布:北京软件行业协会电话 编辑:程序博客网 时间:2024/05/29 18:02

CodeForces - 600C

C. Make Palindrome
time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
Description
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*10^5) 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

题意:改变最少的字符,得到回文字符串,原字符串的字母位置可任意调换,若有多种可能,输出字典序最小的回文串。

思路:记录下每个字母出现次数,优先选择较小的字母。如果有奇数个,则改变最大的字母,使当前最小的奇数个的字母有偶数个。

#include<cstdio>#include<cstring>using namespace std;const int maxn = 2e5 + 5;char s[maxn],ans[maxn];int vis[256];int main(){    while(~scanf("%s",s)){        int len = strlen(s);        int num = 0;        for(int i = 0; i < len; i++){            vis[s[i]] ++;        }        for(char i = 'a'; i <= 'z'; i++){            if(vis[i] & 1) num ++;        }        num >>= 1; //要改变奇数个的字母的次数        bool flag = false;        int top = 0;        for(char i = 'a'; i <= 'z'; i++){ //处理奇数个的字母            if(vis[i] & 1){                if(num) { //还存在要改变字母的情况,当前字母出现次数++,情况数--;                    vis[i] ++;                    num--;                } else { /*如果长度为奇数,那么下一个就为最中间的字母,剩下的奇数个的都减一成偶数*/                    if((len & 1) && !flag){                        top = i;                        flag = true;                    } else {                        vis[i] --;                    }                }            }        }        int now = 0;        for(char i = 'a'; i <= 'z'; i++){            while(vis[i] >= 2){                ans[now] = i;                ans[len - now -1] = i;                vis[i] -= 2;                now ++;            }        }        if(len & 1) ans[len >> 1] = top;        ans[len] = '\0';        printf("%s\n",ans);    }    return 0;}
0 0