A - Anagram -“浪潮杯”第九届山东省ACM大学生程序设计竞赛重现赛

链接:https://www.nowcoder.com/acm/contest/123/A
来源:牛客网

题目描述
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.

输入描述:
There will be multiple test cases. For each testcase:

There is two strings A and B in one line.∣A∣=∣B∣≤50. A and B will contain only uppercase letters
from the English alphabet (‘A’-‘Z’).
输出描述:
For each test case, output the minimal number of
operations.
示例1
输入

ABCA BACA
ELLY KRIS
AAAA ZZZZ
输出

0
29
100

[分析]
一开始以为是有顺序的,但其实要无序。就很简单。贪心就好了。找到离这个字母最近的字母。

首先记录两个字符串都有什么字符,有几个,放在ac[26]和bc[26]里面.
将相同的字符去掉
然后遍历ac,当有字符存在时按字母表顺序向后找,找到的第一个就是最近的,然后在答案里加上当前距离就可以了。

[代码]

#include<cstdio>
#include<algorithm>
#include<cstring>
#include<algorithm>
using namespace std;
int acc[26], bcc[26];
char a[55], b[55];
int main()
{

    while (scanf("%s%s", a, b) != EOF)
    {
        memset(acc, 0, sizeof(acc));
        memset(bcc, 0, sizeof(bcc));
        int len = strlen(a);
        for (int i = 0; i < len; i++)
        {
            acc[a[i] - 'A']++;
            bcc[b[i] - 'A']++;
        }
        for (int i = 0; i < 26; i++)
        {
            int now = min(acc[i], bcc[i]);
            acc[i] -= now;
            bcc[i] -= now;
        }
        int ans = 0;
        for (int i = 0; i < 26; i++)
        {
            while (acc[i])
            {
                for (int j = i + 1; j%26 != i; j++)
                {
                    if (bcc[j%26])
                    {
                        int now = min(acc[i], bcc[j % 26]);
                        acc[i%26] -= now;
                        bcc[j%26] -= now;
                        ans += (j - i)*now;
                    }
                }
            }
        }
        printf("%d\n", ans);
    }
}

猜你喜欢

转载自blog.csdn.net/q435201823/article/details/80375936