Kirinriki
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 1469 Accepted Submission(s): 588
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
8
/*
题意
定义两个字符串的距离dis = Σ| Ai - Bn-1-i |
给你一个字符串s, 问你s子串中dis<=m的最大长度是多少,两个子串不能有公共部分
题解
二分长度,因为不能有重叠部分那么最长就是len/2.
如果在当前长度下存在一对子串满足dis<=m那么更新ans并更新区间
问题是判断dis<=m如果直接暴力会超时。这里使用数组dp
dp[i][j]表示从区间[i,j]以终点分割的两个子串的dis
那么任意起点为i和j长度为l的两个子串的dis = dp[i][j+l-1] - dp[i+1][j-1]
dp数组预处理:dp[i][j] = dp[i+1][j-1] + abs(s[i]-s[j])
dp使用int 会空间超限,使用short会超范围。使用unsigned short刚好
复杂度n^2logn
*/
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
using namespace std;
const int maxn = 5000+10;
int m;
char s[maxn];
unsigned short dp[maxn][maxn];
int len;
bool ok(int l){
for(int i = 0;i<len;++i){
for(int j = i+l;j<len;++j){
if(j+l-1 >= len) break;
if(dp[i][j+l-1] - dp[i+l][j-1]<=m)
return true;
}
}
return false;
}
int main()
{
int t;
scanf("%d", &t);
while (t > 0){
t--;
scanf("%d", &m);
scanf("%s",s);
len = strlen(s);
///预处理dp
for(int l = 1; l <=len; ++l){///区间长度
for(int i = 0; i < len; ++i){
int j = i+l-1;
if(j>=len) continue;
dp[i][j] = dp[i+1][j-1] + abs(s[i]-s[j]);
}
}
int l = 1;
int r = len/2;
int ans = 0;
while(l<=r){
int mid = (l+r)>>1;
if(ok(mid)){
ans = mid;
l = mid+1;
}
else r = mid-1;
}
printf("%d\n",ans);
}
return 0;
}