Kirinriki
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 1495 Accepted Submission(s): 604
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
//
题意
:
PS:Kirinriki:麒麟奇,神奇宝贝。
一个字符串里找两个长度相同的子串,两个子串不能重叠,两个子串的距离必须<=m,m已知,距离的算法题目里也已给出,问子串的最大长度。
//
官方题解
:
两个不重合的子串向中心一起延长会形成奇偶长度两种合串。
枚举一下中心向外延伸,如果和超过了阈值弹掉中心处的位置。
双指针维护。
时间复杂度 O(n2)
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <cmath>
#include <algorithm>
using namespace std;
const int MAX = 5000 + 100;
int m, len;
char str1[MAX];
char str2[MAX];
//尺取法
int work(char *str)
{
int ans = 0;
for (int i = len - 1; i >= 0; i--)
{
int cnt = (i + 1) / 2 - 1;
int sum = 0, num = 0, pos = 0;
for (int j = 0; j <= cnt; j++)
{
sum += abs(str[j] - str[i - j]);
if (sum > m)
{
sum -= abs(str[pos] - str[i - pos]);
sum -= abs(str[j] - str[i - j]);
num--;
pos++;
j--;
}
else
{
num++;
ans = max(ans, num);
}
}
}
return ans;
}
int main()
{
int T;
scanf("%d", &T);
while (T--)
{
scanf("%d", &m);
scanf("%s", str1);
len = strlen(str1);
for (int i = 0; i < len; i++)
{
str2[i] = str1[len - i - 1];
}
int res = 0;
res = max(res, work(str1));
res = max(res, work(str2));
printf("%d\n", res);
}
return 0;
}