2018黑龙江省赛 Similar Strings

Similar Strings

时间限制: 1 Sec  内存限制: 128 MB
提交: 18  解决: 9
[提交] [状态] [讨论版] [命题人:admin]

题目描述

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.

 

输入

The input starts with one line contains exactly one positive integer T which is the number of test cases.
Each test case contains three lines. The first line contains an integer K and each of the following two lines contains a string indicates string A or string B

 

输出

For each test case, output one line containing “y” where y is the maximum s.

 

样例输入

3
3
qwertypoi
qwetyrio
0
qqqqq
qqqaqqqq
10
qwertyuiop
asdfghjklzxcvbnm

 

样例输出

6
4
10

 

提示

1≤T≤5,1≤len(A),len(b)≤4000,0≤K≤min⁡{len(A),len(B)}
Strings only contain lowercase English letters.

 

题目大意给你T组输入,每组输入给你一个k和两个字符串,从两个字符串中各选出一个等长的子串,要求这两个子串上相同位置上不同元素的个数不能超过k,求选出的子串的最大长度是多少。

解法就是从一个字符串中从头开始选取子串在另一个字符串上进行尺取,反过来再尺取一次即可。

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 5005;
int k;
char str1[maxn],str2[maxn];
int ans;
void doit(char str[], char strr[])
{
    int l = min(strlen(str), strlen(strr));
    int cnt,ll,rr;
    rr = -1;
    cnt = 0; //记录当前有几个位置上的字符不同
    for (int ll = 0; ll < l; ++ll) //右移左端点
    {
        while (rr + 1 < l)
        {
            if (str[rr + 1] != strr[rr + 1])
            {
                if (cnt + 1 > k) // 如果不同字符的个数未超过k,则继续右移右端点
                    break;
                cnt++;
            }
            rr++;
        }
        ans = max(ans, rr - ll + 1);
        if (str[ll] != strr[ll])
            --cnt;
    }
}
int main()
{
//    freopen("in.txt", "r", stdin);
    int t;
    scanf("%d", &t);
    while (t--)
    {
        ans = 0;
        scanf("%d", &k);
        scanf("%s%s", str1, str2);
        int l = strlen(str1);
        for (int i = 0; i < l; i++)
            doit(str1 + i, str2); //对第一个字符串进行尺取
        l = strlen(str2);
        for (int i = 0; i < l; i++) 
            doit(str2 + i, str1); //对另一个字符串进行尺取
        printf("%d\n", ans);
    }
    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章