原题链接
Problem Description
Input
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
题目大意
给定一个字符串,要找出它的两个长度相同的子串,使得这个长度尽量长,并且满足两个子串的“距离”小于给定的m。
解题思路
可以枚举子串的中心位置,然后采取尺取的方式向左右两边延伸出去,复杂度O(n^2),没什么坑点比较良心。
AC代码
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cctype>
#include<algorithm>
#include<cmath>
#include<vector>
#include<string>
#include<queue>
#include<list>
#include<stack>
#include<set>
#include<map>
#define ll long long
#define ull unsigned long long
#define db double
//#define rep(i,n) for(int i = 0;i < n; i++)
#define rep(i,a,b) for(int i=(a);i<(b);++i)
#define fil(a,b) memset((a),(b),sizeof(a))
#define cl(a) fil(a,0)
#define pb push_back
#define mp make_pair
#define exp 2.7182818
#define PI 3.141592653589793
#define inf 0x3f3f3f3f
#define fi first
#define se second
#define eps 1e-8
#define MOD 1000000007ll
#define sign(x) ((x)>eps?1:((x)<-eps?(-1):(0)))
using namespace std;
int main()
{
int t,lim;
int sti;
char in[5555];
cin>>t;
while(t--)
{
scanf("%d",&lim);
scanf("%s",in);
int sz=strlen(in);
int maxa=0;
if(sz==2)
{
if(abs(in[0]-in[1])<=lim) printf("1\n");
else printf("0\n");
}
else
{
//枚举奇数中点
for(int i=1;i<sz-1;++i)
{
sti=abs(in[i+1]-in[i-1]);
int st=1;int ed=1;
while(i+ed<sz&&i-ed>=0)
{
if(sti<=lim)
{
maxa=max(maxa,ed-st+1);
ed++;
if(!(i+ed<sz&&i-ed>=0)) break;
sti+=abs(in[i+ed]-in[i-ed]);
}
else
{
sti-=abs(in[i+st]-in[i-st]);
st++;
}
}
}
//枚举偶数中点
for(int i=0;i<sz-1;++i)
{
sti=sti=abs(in[i+1]-in[i]);
int st=1;int ed=1;
while(i+ed<sz&&i-ed+1>=0)
{
if(sti<=lim)
{
maxa=max(maxa,ed-st+1);
ed++;
if(!(i+ed<sz&&i-ed+1>=0)) break;
sti+=abs(in[i+ed]-in[i-ed+1]);
}
else
{
sti-=abs(in[i+st]-in[i-st+1]);
st++;
}
}
}
printf("%d\n",maxa);
}
}
return 0;
}