HUAS Summer Trainning #3~E

Description

Today on a lecture about strings Gerald learned a new definition of string equivalency. Two strings a and b of equal length are calledequivalent in one of the two cases:

  1. They are equal.
  2. If we split string a into two halves of the same size a1 and a2, and string b into two halves of the same size b1 and b2, then one of the following is correct:
    1. a1 is equivalent to b1, and a2 is equivalent to b2
    2. a1 is equivalent to b2, and a2 is equivalent to b1

As a home task, the teacher gave two strings to his students and asked to determine if they are equivalent.

Gerald has already completed this home task. Now it's your turn!

Input

The first two lines of the input contain two strings given by the teacher. Each of them has the length from 1 to 200 000 and consists of lowercase English letters. The strings have the same length.

Output

Print "YES" (without the quotes), if these two strings are equivalent, and "NO" (without the quotes) otherwise.

Sample Input

Input
aaba
abaa
Output
YES
Input
aabb
abab
Output
NO

Hint

In the first sample you should split the first string into strings "aa" and "ba", the second one — into strings "ab" and "aa". "aa" is equivalent to "aa"; "ab" is equivalent to "ba" as "ab" = "a" + "b", "ba" = "b" + "a".

In the second sample the first string can be splitted into strings "aa" and "bb", that are equivalent only to themselves. That's why string "aabb" is equivalent only to itself and to string "bbaa".

解题思路:这个题目用暴力、DFS来求解最好,为了提高效率,首先就要判断输入的字符串是奇数还是偶数,字符串长度为奇数时直接比较两个字符串相不相等,字符串长度为偶数时,平分字符串,像题目的案例那样比较。如果不相等继续分,一直到字符串长度为奇数时,再看字符串长度为奇数时直接比较两个字符串相不相等,首先比较两个字符串是否完全一样,用strncmp函数。相等就直接输出YES,不相等就判断字符串的长度,分偶数跟奇数,拆分好就比较。运用这种方法更能够提高效率,去掉一些不必要的代码,减少时间上的错误。

程序代码:

#include<iostream>
#include<string>
#include<cstring>
using namespace std;
const int m = 200010;
char s1[m], s2[m];
bool dfs(char *a,char *b,int n)
{
    if (strncmp(a, b, n) == 0)              //比较字符串
        return true;
    if (n % 2 != 0)                          //判断字符串长度为偶数还是奇数
        return false;
    int len = n / 2;                        //平分字符串
   
    if (dfs(a, b + len, len) && dfs(a + len, b, len))
        return true;                                   
    if (dfs(a, b, len) && dfs(a + len, b + len, len))    //拆分后的字符串比较
        return true;
    return false;
}
int main()
{
      cin >> s1;
      cin >> s2;
    
      cout <<( dfs(s1, s2, strlen(s1)) ? "YES" : "NO") << endl;
   
    return 0;
}

原文地址:https://www.cnblogs.com/chenchunhui/p/4693195.html