来源:牛客网
Anagram
空间限制:C/C++ 65536K,其他语言131072K
64bit IO Format: %lld
题目描述
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.
输入
ABCA BACA
ELLY KRIS
AAAA ZZZZ
输出
0
29
100
题目给出两个字符串A、B,这两个字符串都由'A'-'Z'构成,字符串X是字符串B任意颠倒字符顺序构成的,求由字符串A转变到字符串X的最少操作数,如A->B,1步 ;B->A,25步(可以看成Z、A相连成环)
思路:先将字符串A、B分别排序,如果a[i]<=b[j]依次寻找距离字符a[i]最近的字符b[j],如果a[i]>b[j],则将剩下的配对(这里不需要考虑配对的次序,可以自己举例)
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
char a[50],b[50];
int len,ans,num;
int judge(char a,char b)
{
int sum=0;
if(a<=b)sum+=b-a;
else sum+=26-(a-b);
return sum;
}
char cmp(char x,char y)
{
return x<y;
}
int main()
{
while(cin>>a>>b)
{
num=0;
len=strlen(a);
sort(a,a+len,cmp);
sort(b,b+len,cmp);
for(int i=0;i<len;i++)
{
for(int j=0;j<len;j++)
{
if(b[j]!=0)
{
if(b[j]>=a[i])
{
num+=judge(a[i],b[j]);
b[j]=0;//标记b[j]是否配对成功
a[i]=0;//标记a[i]是否配对成功
break;
}
}
}
}
for(int i=0;i<len;i++)
{
if(a[i]!=0)
{
for(int j=0;j<len;j++)
{
if(b[j]!=0)//剩下的必为a[i]>b[j]
{
num+=judge(a[i],b[j]);
b[j]=0;
break;
}
}
}
}
cout<<num<<endl;
}
return 0;
}