CodeForces 254C 字典序

来源:互联网 发布:cassandra 导出数据库 编辑:程序博客网 时间:2024/06/05 07:23

Description

input
input.txt
output
output.txt

String x is an anagram of string y, if we can rearrange the letters in string x and get exact string y. For example, strings "DOG" and "GOD" are anagrams, so are strings "BABA" and "AABB", but strings "ABBAC" and "CAABA" are not.

You are given two strings s and t of the same length, consisting of uppercase English letters. You need to get the anagram of string t from string s. You are permitted to perform the replacing operation: every operation is replacing some character from the string s by any other character. Get the anagram of string t in the least number of replacing operations. If you can get multiple anagrams of string t in the least number of operations, get the lexicographically minimal one.

The lexicographic order of strings is the familiar to us "dictionary" order. Formally, the string p of length n is lexicographically smaller than string q of the same length, if p1 = q1p2 = q2, ..., pk - 1 = qk - 1pk < qk for some k (1 ≤ k ≤ n). Here characters in the strings are numbered from 1. The characters of the strings are compared in the alphabetic order.

Input

The input consists of two lines. The first line contains string s, the second line contains string t. The strings have the same length (from 1to 105 characters) and consist of uppercase English letters.

Output

In the first line print z — the minimum number of replacement operations, needed to get an anagram of string t from string s. In the second line print the lexicographically minimum anagram that could be obtained in z operations.

Sample Input

Input
ABACBA
Output
1ABC
Input
CDBABCADCABD
Output
2ADBADC

题意:输入两个长度相同的字符串s,t,要求对s进行最少的改动(每次替换一个字母)使s成为t的重组字(字幕出现次序相同,不要求顺序),如果存在多种改动情况,输出最小字典序的那个。

思路:难点在于字典序,这里引入一个松弛概念,如果s中剩余x个D,而需要替换掉x个D,它是不松弛的,遇到D则一定要把它替换掉,而s中剩余x个D,需要替换掉小于x个D,那么它是松弛的,贪心思想,如果替换掉使s字典序变小,那就换,否则就不换。


#include<cstdio>#include<algorithm>#include<string>#include<cstring>#include<sstream>#include<iostream>#include<cmath>#include<queue>#include<map>using namespace std;int main(){freopen("input.txt","r",stdin);freopen("output.txt","w",stdout);map<char,int> cnts,cnt;vector<char> ch;string s,t;//    char s[10005],t[10005];cin>>s>>t;for(int i=0;i<s.size();i++){cnts[s[i]]++;cnt[s[i]]++;}for(int i=0;i<t.size();i++){cnt[t[i]]--;}int num=0;for(int i=0;i<s.size();i++){cnts[s[i]]--;if(cnt[s[i]]>0){//需替换 if(cnts[s[i]]+1<=cnt[s[i]]){ //不松弛,一定替换 //    printf("debug\n");for(char j='A';j<='Z';j++){if(cnt[j]<0){cnt[s[i]]--;s[i]=j;cnt[j]++;num++;break;}}}else{ //松弛,只替换使字典序变小的 for(int j='A';j<='Z';j++){if(j>s[i])  break;if(cnt[j]<0){cnt[s[i]]--;s[i]=j;cnt[j]++;num++;break;;}}}}}cout<<num<<"\n"<<s<<endl;return 0;}




0 0
原创粉丝点击