A.Anagram
原题链接
https://ac.nowcoder.com/acm/contest/123/A
思路
题目的意思是说,最少经过多少次变化,能将一个串变为另一个串的相似串,相似串的意思是:两个串中同样的字母数相同,例如:ABCD和BADC。那么对于这个题看数据范围只有50可以轻易的想到暴力枚举即可,时间复杂度O(n^2),对于第一个串,枚举第二个串中的每个字母,看哪一个字母可以经过最少的步骤变过去,那么他们两个就凑成一对(贪心)。
代码
#include <iostream>
#include <string.h>
#include <algorithm>
using namespace std;
const int N = 100;
char a[N], b[N];
bool st[N];
int main()
{
while (scanf("%s %s", a, b) != EOF)
{
memset(st, false, sizeof st);
int lena = strlen(a);
int ans = 0;
for (int i = 0; i < lena; i ++ )
{
int r = 30; // 记录最小的交换次数
int p; // 记录交换位置
for (int j = 0; j < lena; j ++ )
{
if (!st[j])
{
if (a[i] <= b[j])
{
if (b[j] - a[i] < r)
{
r = b[j] - a[i];
p = j;
}
}
else
{
int t = (int)('Z' - a[i]) + (int)(b[j] - 'A') + 1;
if (t < r)
{
r = t;
p = j;
}
}
}
}
st[p] = true; // 标记这个位置被用过
ans += r;
}
cout << ans << endl;
}
return 0;
}
浙公网安备 33010602011771号