HDU-6103
Kirinriki
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 1204 Accepted Submission(s): 475
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.
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
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
Source
2017 Multi-University Training Contest - Team 6
我們應該考慮如何才能找到區間最大長度 滿足條件的
由于若A,B滿足條件那么A,B的子串長度就必然滿足條件?? 由于單調性原則?? 長到一定限度就不滿足
而低于m又可以增加長度?? 考慮尺取法
如何尺取?
我們可以枚舉左串的起點 和 右串的終點 因為這樣必然最大子串長度在這個枚舉之中
然后最每一次枚舉
我們用尺取法尺取區間長度 如果此時dis小于m那么就可以向中間延伸 如果大于m那么就不斷地把兩邊去掉
復雜度O(n^2)
code:
#include<bits/stdc++.h> using namespace std; int m;//25000000 string ll; int solve(int l,int r) {int st=0,ed = 0,dis=0;int ma=0;while(l+ed<r-ed){int t = abs(ll[l+ed]-ll[r-ed]);if(dis+t<=m){dis+=t;ed++;ma = max(ma,ed-st);}else{dis-=abs(ll[l+st]-ll[r-st]);st++;}}return ma; } int main() {int t;scanf("%d",&t);while(t--){scanf("%d",&m);getchar();getline(cin,ll);int ans = 0;int len = ll.length();for(int i=1;i<len;i++)ans = max(ans,solve(0,i));for(int i=0;i<len-1;i++)ans = max(ans,solve(i,len-1));printf("%d\n", ans);}return 0; }總結
- 上一篇: 《算法之道》精华 经典算法部分
- 下一篇: 【动态规划】【线段树】 Codeforc