We define the distance of two strings A and B with same length n is
disA,B=∑i=0n−1|Ai−Bn−1−i|
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.
disA,B=∑i=0n−1|Ai−Bn−1−i|
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
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
找给定的字符串的两个子串,他们的距离定义为:disA,B=∑i=0n−1|Ai−Bn−1−i|。求使得距离小于等于m5
的最长子串。
思路:答案肯定具有二分性质的,所以考虑二分枚举答案,然后考虑怎么求得子串的距离。
我们可以知道,对于一个字符串:abcdefedcb。第一个字符串从前往后,第二个字符串从后往前做枚举,例如:
abc匹配dcb那么就是:
abc
bcd(相同位置相减)
那么下一次,前后同时移动一个位置:
bcd
cde
那么前后之后一个位置不同,其他位置相同,那么我们就可以在o(1)时间内求得这两个串的dis。
具体实现看代码,有两次双重循环。
这样代码就是n*n*log(n),实际复杂度在n*n以内(反正跑了1600ms+)
#include <iostream>
#include<stdio.h>
#include<string.h>
#include<algorithm>
#define siz 5005
const int maxn = 5000;
typedef long long LL;
using namespace std;
int m,len;
char str[maxn+15];
bool ok(int l)
{
int cot = 0,s,t;
for(int i=1;i+l*2-1<=len;i++)
{
cot= 0 ;
for(int j=0;j<l;j++) cot+=abs(str[i+j]-str[len-j]);
if(cot<=m) return true;
s = i+1, t = len-1;
while(t-s+1>=l*2)
{
cot = cot + abs(str[s+l-1]-str[t-l+1]) - abs(str[s-1]-str[t+1]);
if(cot<=m) return true;
s++,t--;
}
}
cot = 0;
for(int i=len;i>=l*2;i--)
{
cot = 0;
for(int j=0;j<l;j++) cot+=abs(str[i-j]-str[j+1]);
if(cot<=m) return true;
s = i-1,t = 2;
while(s-t+1>=l*2)
{
cot = cot - abs(str[s+1]-str[t-1]) + abs(str[s-l+1]-str[t+l-1]);
if(cot<=m) return true;
s--,t++;
}
}
return false;
}
void solve()
{
int l=0,r=len/2+1,mid,ans=0;
while(r-l>1)
{
mid = (l+r)>>1;
if(ok(mid)) l = mid,ans = max(ans,mid);
else r = mid;
}
printf("%d\n",ans);
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
scanf("%d",&m);
scanf("%s",str+1);
len = strlen(str+1);
solve();
}
return 0;
}
abcdef