HDU6485 Similar Strings

http://acm.hdu.edu.cn/showproblem.php?pid=6485

Problem Description
Putting two similar strings together will create a very strong power that can quake the earth into parts and the person who did that can be called the Destroyer of the World. In order to stop the Destroyer of the World, WNJXYK decided to check every string in this world to make sure there is no pair of strings are similar. But some strings are too long that WNJXYK cannot judge whether they are similar to others, so he turns to you for help.
Now WNJXYK need you to determine the maximum s, for string A has a substring A’ and string B has a substring B’ whose length are both s and they differ on at most K positions.

题意:給定两个字符串s和t,在s和t中取登长的子串,需要满足最多k位不一样,求最长的子串。
思路:暴力的方法就是枚举子串,比较不同位数,复杂度 O ( n 3 ) O(n^3) O(n3)
其实可以这样:s整个串+枚举t的后缀+尺取求最长符合要求的子串,再来一遍t整个串+枚举s的后缀+尺取求最长符合要求的子串。复杂度 O ( n 2 ) O(n^2) O(n2)
为什么可以这样的?
如下图,假设最优的子串是黑色的线段,那么将它左移红色线段那么长,一定由此尺取转移来,因此这个方法是正确的。
HDU6485 Similar Strings_第1张图片

#include
using namespace std;
#define maxn 5000

int T,k,ans;
char s[maxn],t[maxn];

void solve(char *s,char *t)
{
    int ls=strlen(s),lt=strlen(t);
    int l=0,r=-1,cnt=0;
    while(l<ls)
    {
        while(cnt<=k&&r<lt)
        {
            ++r;
            if(r==lt)break;
            if(s[r]!=t[r])cnt++;
        }
        ans=max(ans,r-l);
        if(s[l]!=t[l])cnt--;
        l++;
    }
}

int main()
{
    //freopen("input.in","r",stdin);
    cin>>T;
    while(T--)
    {
        ans=0;
        cin>>k>>s>>t;
        int ls=strlen(s),lt=strlen(t);
        for(int i=0;i<ls;i++)solve(s+i,t);
        for(int i=0;i<lt;i++)solve(s,t+i);
        cout<<ans<<endl;
    }
}

你可能感兴趣的:(尺取)