We define the distance of two strings A and B with same length n is
The difference between the two characters is defined as the difference in ASCII.
You should find the maximum length of two non-overlapping substrings in given string S, and the distance between them are less then or equal to m.
Input
The first line of the input gives the number of test cases T; T test cases follow.
Each case begins with one line with one integers m : the limit distance of substring.
Then a string S follow.
Limits
T≤100
0≤m≤5000
Each character in the string is lowercase letter, 2≤|S|≤5000
∑|S|≤20000
Output
For each test case output one interge denotes the answer : the maximum length of the substring.
Sample Input
1
5
abcdefedcb
Sample Output
5
Hint
[0, 4] abcde
[5, 9] fedcb
The distance between them is abs(‘a’ - ‘b’) + abs(‘b’ - ‘c’) + abs(‘c’ - ‘d’) + abs(‘d’ - ‘e’) + abs(‘e’ - ‘f’) = 5
题意:
给你一个字符串,让你求出距离不超过m的两个不重叠的最长子串,距离在上面有定义。
题解:
一开始想着二分,结果check函数写不出来,看了别人的代码发现这个想法很简单但是又很容易想不到。这两个串的中间字符只有偶数和奇数的情况,那么枚举每一个点作为对称的中点,两个字符串相隔偶数和奇数的情况。之后check就是尺取了。
#include<bits/stdc++.h>
using namespace std;
char s[5005];
int len,m,ans;
void check(int x,int y)
{
int l=0,r=0,dis=0;
while(y+r<len&&x-r>=0)
{
if(dis+abs(s[y+r]-s[x-r])<=m)
{
dis+=abs(s[y+r]-s[x-r]);
ans=max(ans,r-l+1);
r++;
}
else
{
dis-=abs(s[y+l]-s[x-l]);
l++;
}
}
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
scanf("%d",&m);
scanf("%s",s);
len=strlen(s);
ans=0;
for(int i=0;i<len;i++)
check(i-1,i+1),check(i,i+1);
printf("%d\n",ans);
}
return 0;
}