山東省第九屆省賽ACM重現賽 A-Anagram
阿新 • • 發佈:2018-11-09
A-Anagram
連結: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
For example, she can transform “ELLY
輸入描述:
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
題目解析
這道題是省賽的A題,題面比較長但是大體意思比較簡單。其實就是我們在第一個字串中依次取字元和第二個字串中的每個字元進行挨個的比較。選出最小的距離然後依次相加,最後得到一個距離和叫做sum並進行輸出。
給定兩個字串,假設是ELLY與KRIS,E到K是6,L到R是6,當第二個L到I時,L是比I大的,此時L就要繞到Z,從Z到A,再從A開始到I,這樣長度就是23,Y到S同理,長度是20;這樣找完之後序列長度之和就是6 +6+23+20=55.這是題目中給出的一種解答。但是題目要求我們找字元間最小的長度,我就把第一個字串中的每一個字元與第二個字串中的每一個字元比較,每次都找出最短的長度,然後加在一起即可。
題目原始碼
#include<iostream>
#include<cstdio>
#include<stdlib.h>
#include<vector>
#include<algorithm>
using namespace std;
char str1[55],str2[55];
char s1[55],s2[55];
int vis[100];
const int maxn=1<<30;
int main(){
while(~scanf("%s %s",str1,str2)){
memset(vis,0,sizeof(vis));//將訪問陣列初始化為未訪問
int sum=0;
int len1 = strlen(str1);
int len2 = strlen(str2);
for(int i=0;i<len1;i++)
s1[i]=str1[i];
for(int i=0;i<len2;i++)
s2[i]=str2[i];
for(int i=0;i<len1;i++){
int minn=maxn;
int temp;
for(int j=0;j<len2;j++){
if(vis[j]==0){
//如果未訪問過
if((s1[i]-'0')-(s2[j]-'0')>0){
//字串1的ascii大於字串2的ascii
if(abs((s1[i]-'0')-(s2[j]-'0')-26)<minn)
{
minn=abs((s1[i]-'0')-(s2[j]-'0')-26);
temp=j;
}
}
else{
if(abs((s1[i]-'0')-(s2[j]-'0'))<minn){
minn=abs((s1[i]-'0')-(s2[j]-'0'));
temp=j;
printf("minn2=%d\n",minn);
}
}
}
}
vis[temp]=1;
sum+=minn;
}
printf("%d\n",sum);
}
return 0;
}