Kirinriki
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 1086 Accepted Submission(s): 432
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
题意:给定m和一个字符串,定义两个字符串的dis两者对应字符字典序之差,对应方式为一个从前到后,一个从后到前。然后给定一个m,先要求出最长的给定字符串的两个子串满足它们之间的dis小于等于m的长度。
题解:由于是类似回文串,于是可以想到枚举中点,同时结合尺取可以找到最大。(这里注意枚举中点有奇偶两种情况)
代码:
#include <cstdio>
#include <iostream>
#include <cstring>
#include <string>
#include <cstdlib>
#include <algorithm>
#include <queue>
#include <vector>
#include <set>
#include <stack>
#include <map>
#include <cmath>
#include <functional>
#include<ctime>
using namespace std;
typedef long long ll;
typedef pair<int, int> P;
const int maxn = 5e3+7;
int m;
char s[5005];
int ans;
int main(){
int t;
scanf("%d",&t);
while(t--){
ans = 0;
scanf("%d %s",&m,s);
int n = strlen(s);
for(int i = 0;i < n;i++){
int sum = 0;
for(int r = i,l = i,pr = r,pl = l;l >= 0&&r < n;++r,--l){
sum+=abs(s[r]-s[l]);
while(pr<=r&&sum>m) sum-=abs(s[pr++]-s[pl--]);
ans = max(ans,r-pr+(pr!=i));
}
}
for(int i = 1;i < n;i++){
int sum = 0;
for(int r = i,l = i-1,pr = r,pl = l;l >= 0&&r < n;r++,l--){
sum+=abs(s[r]-s[l]);
while(pr<=r&&sum>m) sum-=abs(s[pr++]-s[pl--]);
ans = max(ans,r-pr+1);
}
}
printf("%d\n",ans);
}
return 0;
}