Discription
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 = q1, p2 = q2, …, pk - 1 = qk - 1, pk < 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 1 to 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.
Examples
Input
ABA
CBA
Output
1
ABC
Input
CDBABC
ADCABD
Output
2
ADBADC
Note
The second sample has eight anagrams of string t, that can be obtained from string s by replacing exactly two letters: “ADBADC”, “ADDABC”, “CDAABD”, “CDBAAD”, “CDBADA”, “CDDABA”, “DDAABC”, “DDBAAC”. These anagrams are listed in the lexicographical order. The lexicographically minimum anagram is “ADBADC”.
题意
给定两个字符串t和s
要求改变t中的一些字符使t和s所含字符相同(顺序可以不同)
求出最小的改变次数,以及改变之后字典序最小的字符t。
思路
用两个数组num1,num2分别记录连哥哥字符串种字符个数。若s1某类的字符数大于s2的,则需要将该类字符替换成s2中多于s1的字符,比关切保证替换后的字符字典序小于替换之前的字符。
AC代码
#include<bits/stdc++.h>
using namespace std;
int num1[30],num2[30];
string s1,s2;
int main()
{
ios::sync_with_stdio(false);
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
cin>>s1>>s2;
for(int i=0; i<s1.size(); i++)
{
num1[s1[i]-'A']++;
num2[s2[i]-'A']++;
}
int x;
int ans=0;
for(int i=0; i<s1.size(); i++)
{
x=s1[i]-'A';
if(num1[x]>num2[x])//s2中大于s1中的字符
{
for(int j=0; j<26; j++)
if(num1[j]<num2[j])
{
if(j<x||!num2[x])//满足替换后的字符字典序小于替换之前且说
中个数不为0,则进行替换
{
s1[i]=j+'A';
num2[j]--;
ans++;
}
else
num2[x]--;//不满足条件,则不需要替换,直接减减
break;
}
num1[x]--;
}
}
cout<<ans<<endl;
cout<<s1<<endl;
return 0;
}