Codeforces 559B

559B - Equivalent Strings

思路:字符串处理,分治

不要用substr(),会超时

AC代码:

#include<bits/stdc++.h>
#include<cstring>
using namespace std;
#define ll long long
const int N=2e5+5;
bool cmp(char a[],char b[],int l)
{
    bool ans=true;
    for(int i=0;i<l;i++)if(a[i]!=b[i])ans=false;
    return ans;
}
bool eq(char a[],char b[],int l)
{
    if(cmp(a,b,l))return true;
    if(l&1)return false;
    if(eq(a,b+l/2,l/2)&&eq(a+l/2,b,l/2)||eq(a,b,l/2)&&eq(a+l/2,b+l/2,l/2))return true;
    return false;
}
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    char s1[N],s2[N];
    cin>>s1>>s2;
    if(eq(s1,s2,strlen(s1)))cout<<"YES"<<endl;
    else cout<<"NO"<<endl;
    return 0;
} 

TLE代码:

#include<bits/stdc++.h>
#include<cstring>
using namespace std;
#define ll long long
bool eq(string a,string b)
{
    if(a==b)return true;
    if(a.size()!=b.size())return false;
    if(a.size()&1)return false;
    string a1=a.substr(0,a.size()/2),a2=a.substr(a.size()/2,a.size()/2);
    string b1=b.substr(0,b.size()/2),b2=b.substr(b.size()/2,b.size()/2);
    if((eq(a1,b1)&&eq(a2,b2))||(eq(a1,b2)&&eq(a2,b1)))return true;
    else return false;
}
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    string s1,s2;
    cin>>s1>>s2;
    if(eq(s1,s2))cout<<"YES"<<endl;
    else cout<<"NO"<<endl;
    return 0;
} 
原文地址:https://www.cnblogs.com/widsom/p/7201469.html