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 tfrom 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.
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.
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.
ABA
CBA
1
ABC
CDBABC
ADCABD
2
ADBADC
解题思路:
贪心,设定a[A..Z]为s串中字母出现次数,b[A..Z]为t串中字母出现次数,
我们要解决两个问题: 1. 操作次数最少 2. 同样操作次数,字典序最小
对于问题1: 串s中一个字符i , 当且仅当 a[ s[i] ] > b[ s[i] ] 的时候,我们才考虑时候替换它,若不满足此条件,我们在之后的操作只会更而外多出一次操作,
这显然不是我们想要的。这样,我们就解决了操作次数最少问题。
对于问题2: 在满足上面条件后,我们从[A..Z] 选择一个P, 这里有两种情况。
一. 字符P == s[i] 此时,如果 a[ s[i] ] > 0 && b[ s[i] ] > 0 此时我们保留修改当前s[i]为P 可得到字典徐较小的结果
二. 字符P != s[i] 此时, 如果 a[p] < b[p] ,意味着,我们需要添加p字符到串s中,所以此处需要替换操作.
到这里,结果统计 上面的二执行的次数就是我们需要的结果了...
参考代码:
#include<stdio.h> int n,a[255],b[255],r; char s[100010],t[100010]; int main() { freopen("input.txt", "r", stdin); freopen("output.txt","w", stdout); scanf("%s%s",s,t); for(int i = 0; s[i]; i++) a[s[i]]++; for(int i = 0; t[i]; i++) b[t[i]]++; for(int i = 'A'; i <= 'Z'; i++) r+=a[i]>b[i]?a[i]-b[i]:b[i]-a[i]; int res = 0; for(int i = 0; s[i]; i++) if (a[s[i]]>b[s[i]]) { for(int p = 'A'; p <='Z'; p++ ) if (p==s[i]&&a[p]>0&&b[p]>0) { --a[p];--b[p]; break; } else if (b[p]>a[p]) { --a[s[i]];++a[p];s[i]=p; res += 1; break; } } printf("%d\n%s",res,s); return 0; }