Kirinriki
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 1822 Accepted Submission(s): 749
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
5Hint[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
Source
求最大字串,使得交叉相减绝对值和最大且不超过m的字串长度
处理区间最大问题用尺取法,从a开始枚举,如果枚举的res值超过m,则退回到开头,下次该区间跳过枚举,枚举到最后一个字符时,枚举起始地址+1。
下面举例说明:
1
2
abcd
####0-1=1
####0-2=3
****0-2=1
l ---->0
^^^^0-2=-1
####0-2=1
####0-3=4
****0-3=1
l ---->0
^^^^0-3=-2
####0-3=1
####1-2=2
2
2
abcd
####0-1=1
####0-2=3
****0-2=1
l ---->0
^^^^0-2=-1
####0-2=1
####0-3=4
****0-3=1
l ---->0
^^^^0-3=-2
####0-3=1
####1-2=2
2
带#号的为第一次枚举,*号为超出了m,去掉当前枚举值,^为继续后退,得到新的起始值,继续枚举
最后直到枚举到1-2结束,输出ans=2
#include <stdio.h>
#include <cstring>
#include <algorithm>
#include <iostream>
using namespace std;
const int maxn=20005;
char s[maxn];
int m,len;
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
scanf("%d",&m);
scanf("%s",s);
len=strlen(s);
int ans=0;
for(int i=0;i<len;i++)
{
int t=0,res=0,l=0;
for(int j=0;j<(i+1)/2;j++)
{
res+=abs(s[j]-s[i-j]);
//printf("####%d-%d=%d\n",j,i-j,ans);
if(res<=m)
{
t++;
ans=max(t,ans);
}
else
{
res-=abs(s[j]-s[i-j]);
//printf("****%d-%d=%d\n",j,i-j,ans);
res-=abs(s[l]-s[i-l]);
//printf("l ---->%d\n",l);
//printf("^^^^%d-%d=%d\n",j,i-j,ans);
l++,t--,j--;
}
}
}
reverse(s,s+len);
//cout<<s<<endl;
for(int i=0;i<len;i++)
{
int t=0,res=0,l=0;
for(int j=0;j<(i+1)/2;j++)
{
res+=abs(s[j]-s[i-j]);
if(res<=m)
{
t++;
ans=max(t,ans);
}
else
{
res-=abs(s[j]-s[i-j]);
res-=abs(s[l]-s[i-l]);
l++,t--,j--;
}
}
}
printf("%d\n",ans);
}
}