Description
定义两个长度均为
n
的字符串
Input
第一行一整数
Output
输出
S
的满足距离小于
Sample Input
1
5
abcdefedcb
Sample Output
5
Solution
设两个子串分别是
S[x,x+len]
和
S[y,y+len]
,其中
y>x+len
,那么这两个字符串的距离为
∑i+j=x+y+len|Si−Sj|
,枚举
i+j
的和
k
,得到序列
Code
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
namespace fastIO
{
#define BUF_SIZE 100000
//fread -> read
bool IOerror=0;
inline char nc()
{
static char buf[BUF_SIZE],*p1=buf+BUF_SIZE,*pend=buf+BUF_SIZE;
if(p1==pend)
{
p1=buf;
pend=buf+fread(buf,1,BUF_SIZE,stdin);
if(pend==p1)
{
IOerror=1;
return -1;
}
}
return *p1++;
}
inline bool blank(char ch)
{
return ch==' '||ch=='\n'||ch=='\r'||ch=='\t';
}
inline void read(int &x)
{
char ch;
while(blank(ch=nc()));
if(IOerror)return;
for(x=ch-'0';(ch=nc())>='0'&&ch<='9';x=x*10+ch-'0');
}
inline void readc(char &x)
{
char ch;
while(blank(ch=nc()));
if(IOerror)return;
x=ch;
}
inline void reads(char *x)
{
char ch;
while(blank(ch=nc()));
if(IOerror)return;
int n=0;
while(1)
{
x[n++]=ch;
if(blank(ch=nc()))break;
}
x[n]='\0';
}
#undef BUF_SIZE
};
using namespace fastIO;
const int maxn=5005;
int T,m,a[maxn];
char s[maxn];
int deal(int *a,int n)
{
int l=0,r=0,sum=0,ans=0;
while(l<n)
{
while(r<n&&sum+a[r]<=m)sum+=a[r++];
ans=max(ans,r-l);
sum-=a[l++];
}
return ans;
}
int main()
{
read(T);
//scanf("%d",&T);
while(T--)
{
//scanf("%d",&m);
//scanf("%s",s+1);
read(m);reads(s+1);
int n=strlen(s+1),ans=0;
for(int i=2;i<=2*n;i++)
{
int res=0;
for(int j=1;j<=(i-1)/2;j++)
{
int k=i-j;
if(k<=n)a[res++]=abs(s[j]-s[k]);
}
ans=max(ans,deal(a,res));
}
printf("%d\n",ans);
}
return 0;
}