hdoj-4357-String change

来源:互联网 发布:中级程序员考试报名 编辑:程序博客网 时间:2024/05/12 03:38

Description
In this problem you will receive two strings S 1 and S 2 that contain only lowercase letters.
Each time you can swap any two characters of S 1. After swap,both of the two letters will increase their value by one. If the previous letter is ‘z’,it will become ‘a’ after being swapped.
That is to say ,”a” becomes “b”,”b” becomes “c”…..”z” becomes “a” and so on.
You can do the change operation in S 1 as many times as you want.
Please tell us whether you can change S 1 to S 2 after some operations or not.

Input
There are several cases.The first line of the input is a single integer T (T <= 41) which is the number of test cases.Then comes the T test cases .

For each case,the first line is S 1,the second line is S 2.S 1 has the same length as S 2 and the length of the string is between 2 and 60.

Output
For each case,output “Case #X: ” first, X is the case number starting from 1.If it is possible change S 1 to S 2 output “YES”,otherwise output “NO”.

Sample Input

3
ab
ba

bac
ddb

aaabb
cbccd

Sample Output

Case #1: NO
Case #2: YES
Case #3: YES

Hint

For the first case,it’s impossible to change “ab” to “ba” .

For the second case,swap(S1[0],S1[2])->swap(S1[1],S1[2]),meanwhile:bac->dac->ddb.

For the third case,swap(S1[0],S1[3])->swap(S1[1],S1[2])->swap(S1[2],S1[3])->swap(S1[3],S1[4]),
meanwhile:aaabb->caabb->cbbbb->cbccb->cbccd.

数学思维题,只是要分两种情况讨论一下,当字符串长度大于二和等于二的时候。
大于二的时只需要计算他们的和是不是偶数即可,小于二的时候稍微麻烦一点,但是必须在26步以内完成才行

#include<cstdio>#include<cstring>#include<algorithm>#include<iostream>using namespace std;int main(){    int len,i,s,t,r=1,q;    char a;    char str1[5000],str2[5000];    scanf("%d",&t);    while(t--)    {        scanf("%s",str1);        scanf("%s",str2);        len=strlen(str1);        s=0;q=0;        printf("Case #%d: ",r++);        if(len>2)        {            for(i=0;i<len;i++)            s=s+str1[i]-'a'+str2[i]-'a';        if(s%2==0)            printf("YES\n");        else            printf("NO\n");        }        else if(len==2)        {            if(strcmp(str1,str2)==0)                printf("YES\n");            else            {                while(strcmp(str1,str2)!=0)                {                    a=str1[1]+1;                    if(a>'z')                        a='a';                    str1[1]=str1[0]+1;                    if(str1[1]>'z')                        str1[1]='a';                    str1[0]=a;                    if(q==26)                        break;                    q++;                }                if(q==26)                    printf("NO\n");                else if(q<26)                    printf("YES\n");            }        }    }    return 0;}
0 0
原创粉丝点击