Anagram

本是古典 何须时尚 2022-05-24 02:52 240阅读 0赞

Time Limit: 1000 ms Memory Limit: 65536 KiB

Problem Description
Orz has two strings of the same length: A and B. Now she wants to transform A into an anagram of B (which means, a rearrangement of B) by changing some of its letters. The only operation the girl can make is to “increase” some (possibly none or all) characters in A. E.g., she can change an ‘A’ to a ‘B’, or a ‘K’ to an ‘L’. She can increase any character any times. E.g., she can increment an ‘A’ three times to get a ‘D’. The increment is cyclic: if she increases a ‘Z’, she gets an ‘A’ again.
For example, she can transform “ELLY” to “KRIS” character by character by shifting ‘E’ to ‘K’ (6 operations), ‘L’ to ‘R’ (again 6 operations), the second ‘L’ to ‘I’ (23 operations, going from ‘Z’ to ‘A’ on the 15-th operation), and finally ‘Y’ to ‘S’ (20 operations, again cyclically going from ‘Z’ to ‘A’ on the 2-nd operation). The total number of operations would be 6 + 6 + 23 + 20 = 55. However, to make “ELLY” an anagram of “KRIS” it would be better to change it to “IRSK” with only 29 operations. You are given the strings A and B. Find the minimal number of operations needed to transform A into some other string X, such that X is an anagram of B.

Input
There will be multiple test cases. For each test case:
There is two strings A and B in one line. |A| = |B| \leq 50∣A∣=∣B∣≤50. A and B will contain only uppercase letters from the English alphabet (‘A’-‘Z’).

Output
For each test case, output the minimal number of operations.

Sample Input
ABCA BACA
ELLY KRIS
AAAA ZZZZ
Sample Output
0
29
100
Hint
Source
“浪潮杯”山东省第九届ACM大学生程序设计竞赛(感谢山东财经大学)

  1. #include<stdio.h>
  2. #include<iostream>
  3. #include <iomanip>
  4. #include <string.h>
  5. using namespace std;
  6. void mySort(char a[])
  7. {
  8. int i, j;
  9. int len = strlen(a);
  10. char t;
  11. for(i = 0; i < len - 1; i++)
  12. {
  13. for(j = 0; j < len - i - 1; j++)
  14. {
  15. if(a[j] > a[j+1])
  16. {
  17. t = a[j];
  18. a[j] = a[j+ 1];
  19. a[j+1] = t;
  20. }
  21. }
  22. }
  23. //for(i = 0; i < )
  24. }
  25. int main()
  26. {
  27. char a[102];
  28. char b[102];
  29. while(cin >> a >> b)
  30. {
  31. mySort(a);
  32. mySort(b);
  33. int len = strlen(a);
  34. char c[105];
  35. int i = 0;
  36. int j = 0, k = 0;
  37. int sum = 0;
  38. while(j < len)
  39. {
  40. if(a[i] <= b[j])
  41. {
  42. sum += b[j] - a[i];
  43. i++;
  44. j++;
  45. }
  46. else
  47. {
  48. c[k++] = b[j];
  49. j++;
  50. }
  51. }
  52. if(j == len)
  53. {
  54. j = 0;
  55. while(j < k)
  56. {
  57. sum += c[j] - a[i]+26;
  58. j++;
  59. i++;
  60. }
  61. }
  62. cout << sum << endl;
  63. }
  64. return 0;
  65. }

发表评论

表情:
评论列表 (有 0 条评论,240人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Anagrams问题

    二.                       Anagrams问题 Anagrams指的是具有如下特性的两个单词:在这两个单词当中,每一个英文字母(不区分大小写)所出现

    相关 Anagrams问题

    问题描述   Anagrams指的是具有如下特性的两个单词:在这两个单词当中,每一个英文字母(不区分大小写)所出现的次数都是相同的。例如,“Unclear”和“Nuclear