题目:
Problem Description
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| 的最大长度5
思路:利用尺取法,遍历字符串S的每一个字符,从子串A的末端与子串B的起始端开始计算dis_AB(i-1,i+1)&&((i,i+1)||(i-1,i)->看遍历起始位置),最后查找最长的长度~说不太清,看代码就行,很明了~感谢f_zyj的指点~
CODE:
#include<bits/stdc++.h>
using namespace std;
char s[5005];
int m,ans,cnt,a[2502];
void judge(){
int sum=0,l=0,r=0;
while(r<cnt){
sum+=a[r++];
while(sum>m) sum-=a[l++];
ans=max(ans,r-l);
}
}
void solve(){ //分别计算中间空余偶数个或奇数个字符的情况
int i,l,r,len=strlen(s);
ans=0;
for(i=1;i<len;i++){
cnt=0;
l=i-1,r=i+1;
while(l>=0&&r<len) a[cnt++]=abs(s[l--]-s[r++]);
judge();
}
for(i=1;i<len;i++){
cnt=0;
l=i-1,r=i;
while(l>=0&&r<len) a[cnt++]=abs(s[l--]-s[r++]);
judge();
}
/*for(i=0;i<len;i++){
cnt=0;
l=i,r=i+1;
while(l>=0&&r<len) a[cnt++]=abs(s[l--]-s[r++]);
judge();
}*/
printf("%d\n",ans);
}
int main(){
int t;
scanf("%d",&t);
while(t--){
scanf("%d%s",&m,s);
solve();
}
return 0;
}