Kirinriki
傳送門1
傳送門2
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
Each character in the string is lowercase letter,
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
題意
給出字符串
分析
定義dp[i][j]
表示A串爲區間
然後二分答案,枚舉長度mid
只要滿足dp[i-mid+1][j+mid]-dp[i+1][j]<=m
就表示長度爲mid時可以.
CODE
#include<cstdio>
#include<cstring>
#define N 5005
#define FOR(i,a,b) for(int i=(a),i##_END_=(b);i<=i##_END_;i++)
char s[N];
unsigned short dp[N][N];//開int會炸
int len,m;
inline int abs(int x) {return x>0?x:-x;}
bool check(int mid) {
FOR(i,mid,len-mid)FOR(j,i,len-mid)
if(dp[i-mid+1][j+mid]-dp[i+1][j]<=m)
return 1;
return 0;
}
int main() {
int t;
scanf("%d",&t);
while(t--) {
scanf("%d%s",&m,s+1);
len=strlen(s+1);
FOR(i,1,len)dp[i][i]=0;
FOR(k,2,len)FOR(i,1,len-k+1) {
int j=i+k-1;
dp[i][j]=dp[i+1][j-1]+abs(s[i]-s[j]);
}
int L=1,R=len/2,mid,ans=0;
while(L<=R) {
mid=(L+R)>>1;
if(check(mid))ans=mid,L=mid+1;
else R=mid-1;
}
printf("%d\n",ans);
}
return 0;
}