Kirinriki
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 1590 Accepted Submission(s): 646
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
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
题意:
在s中找两个不重叠且最长的子串,dis(A,B)<=m
解析:
做的时候完全想歪了,等看了题解才想到。
找不重叠子串的过程就类似于在一个串中找最长的回文子串的过程,因为任意满足答案的两个子串都可以向中心延伸(且两子串长度相同),直至相交,这样就可以从他们中心的位置开始向两边搜索,当当前找到的子串dis>m时,就将中心指针往两边移,直至dis<=m为止。
这样就可以用找回文子串类似的方法,分为两子串相距偶数个字符和两子串相距奇数个字符来做
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
const int N = 5010;
int main()
{
int t,m;
char str[N];
scanf("%d",&t);
while(t--)
{
scanf("%d",&m);
scanf("%s",str);
int p1,p2,q1,q2;
int len=strlen(str);
int s,Max;
Max=0;
for(int i=0,j=1;i>=0&&j<len;i++,j++) //两子串相距偶数个字符(包括0)
{
p1=i;
p2=p1-1;
q1=j;
q2=q1+1;
s=abs(str[p1]-str[q1]);
if(s<=m&&1>Max) Max=1;
while(p2>=0&&q2<len)
{
while(s>m&&p1>p2&&q1<q2)
{
s-=abs(str[p1]-str[q1]);
p1--;
q1++;
}
if(p1<=p2||q1>=q2)
{
p2=p1-1;
q2=q1+1;
s=abs(str[p1]-str[q1]);
if(s<=m&&1>Max) Max=1;
}
while(s<=m&&p2>=0&&q2<len)
{
s+=abs(str[p2]-str[q2]);
//if(s>m) break;
p2--;
q2++;
if(p1-p2>Max&&s<=m) Max=p1-p2;
}
}
}
if(Max<len/2)
{
for(int i=1;i<len-1;i++) // 两子串相距奇数个字符
{
p1=i-1;
p2=p1-1;
q1=i+1;
q2=q1+1;
s=abs(str[p1]-str[q1]);
if(s<=m&&1>Max) Max=1;
while(p2>=0&&q2<len)
{
while(s>m&&p1>p2&&q1<q2)
{
s-=abs(str[p1]-str[q1]);
p1--;
q1++;
}
if(p1<=p2||q1>=q2)
{
p2=p1-1;
q2=q1+1;
s=abs(str[p1]-str[q1]);
if(s<=m&&1>Max) Max=1;
}
while(s<=m&&p2>=0&&q2<len)
{
s+=abs(str[p2]-str[q2]);
//if(s>m) break;
p2--;
q2++;
if(p1-p2>Max&&s<=m) Max=p1-p2;
}
}
}
}
printf("%d\n",Max);
}
return 0;
}