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;
}

 

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