Kirinriki
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 1598 Accepted Submission(s): 651
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,就删掉前面的。复杂度O(n * n)#include <bits/stdc++.h> using namespace std; const int maxn = 50000 + 10; char s[maxn]; int m; int main() { //freopen("C:\\Users\\creator\\Desktop\\in1.txt","r",stdin) ; //freopen("C:\\Users\\creator\\Desktop\\out.txt","w",stdout) ; int T; scanf("%d", &T); while(T--) { scanf("%d", &m); scanf("%s", s); int len = strlen(s); int ans = 0; for(int i = 0; i < len; i++)//枚举中间点 { for(int l = i, r = i, value = 0, pl = l - 1, pr = r + 1; l >= 0 && r <= len - 1; l--, r++) { value += abs(s[l] - s[r]); while(pl >= l && value > m) { value -= abs(s[pl] - s[pr]); pl--; pr++; } if(pl >= l) ans = max(ans, pl - l + 1); } } for(int i = 1; i < len; i++) { for(int l = i - 1, r = i, value = 0, pl = l, pr = r; l >=0 && r <= len - 1; l--, r++) { value += abs(s[l] - s [r]); while(pl >= l && value > m) { value -= abs(s[pl] - s[pr]); pl--; pr++; } if(pl >= l) ans = max(ans, pl - l + 1); } } printf("%d\n", ans); } return 0; }