Kirinriki
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 1275 Accepted Submission(s): 503
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
转自:http://blog.youkuaiyun.com/qq_37412229/article/details/77073094
思路:假设i是左边s1串的头位置,j是右边s2串尾位置,那么状态转移的方程不就是看abs(str[j]-str[i])+ len[i+1][j-1])
是否小于等于m(len[i][j]
表示这俩个串所能组成最长子串的花费是多少),如果是直接 dp[i][j] = dp[i+1][j-1] + 1
,否则要逐步的去将上一个状态的长度末尾删去直到满足<=m为止.因为只有俩个状态所以开2就够了,内存问题根本不用担心。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<cmath>
#include<queue>
#include<stack>
#include<vector>
#include<map>
#include<set>
#include<algorithm>
using namespace std;
#define ll long long
#define ms(a,b) memset(a,b,sizeof(a))
#define maxn 510
const int M=1e6+10;
const int MM=2e3+10;
const int inf=0x3f3f3f3f;
const int mod=998244353;
const double eps=1e-10;
int n,m,k;
int len[2][M],dp[2][M];
char str[M];
int main()
{
int t;
scanf("%d",&t);
while(t--){
ms(len,0);
ms(dp,0);
scanf("%d%s",&m,str+1);
int lens=strlen(str+1);
int id=1,ans=0;
for(int i=lens;i>=1;i--,id^=1)
for(int j=i+1;j<=lens;j++){
int u=abs(str[j]-str[i]);
if(u>m){
dp[id][j]=0;len[id][j]=u;
continue;
}
if(len[id^1][j-1]+u<=m)
dp[id][j]=dp[id^1][j-1]+1,len[id][j]=len[id^1][j-1]+u;
else {
int val=len[id^1][j-1],l=dp[id^1][j-1];
while(u+val>m&&l){
val-=abs(str[i+l]-str[j-l]);
l--;
}
dp[id][j]=l+1,len[id][j]=u+val>m?u:u+val;
}
ans=max(ans,dp[id][j]);
}
printf("%d\n",ans);
}
return 0;
}