Kirinriki
Problem Description
We define the distance of two strings A and B with same length n isdisA,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
15
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
2017 Multi-University Training Contest - Team 6
题意:给出一个字符串,从中选取两个不重复的子串,使得dis距离小于等于m,输出最长子串的长度。
题解:类似处理回文串,枚举中心点(要分奇数偶数两种情况枚举),进行尺取,向外延伸,如果超过了m,去掉中心处位置。双指针维护。同时记录最大子串长度。时间复杂度O(n^2)
#include<iostream>
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<vector>
#include<queue>
#include<stack>
#include<math.h>
#define INF 5e9;
using namespace std;
char s[5005];
int get(int i,int j)
{
if(s[i]-s[j]<0)
return s[j]-s[i];
else return s[i]-s[j];
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
int m;
scanf("%d",&m);
scanf("%s",s);
int n=strlen(s);
int ans=0;
for(int i=0;i<n;i++)
{
int l=i,r=i;
int ll=i,rr=i;
int sum=0;
while(1)
{
sum+=get(l,r);
while(sum>m&&ll>=l&&rr<=r)
{
sum-=get(ll,rr);
ll--;
rr++;
}
if(rr==i) ans=max(r-rr,ans);
else ans=max(r-rr+1,ans);
if(l==0||r==n-1) break;
l--;r++;
}
}
for(int i=0;i<n-1;i++)
{
int l=i,r=i+1;
int ll=i,rr=i+1;
int sum=0;
while(1)
{
sum+=get(l,r);
while(sum>m&&ll>=l&&rr<=r)
{
sum-=get(ll,rr);
ll--;
rr++;
}
ans=max(r-rr+1,ans);
if(l==0||r==n-1) break;
l--;r++;
}
}
cout<<ans<<endl;
}
return 0;
}