2017多校训练6-1008:Kirinriki(HDU6103)

本文介绍了一种寻找给定字符串中两个非重叠子串的方法,通过计算这些子串间的距离(基于字符ASCII值之差),并利用二分法高效地找出满足特定距离条件的最大长度子串。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

We define the distance of two strings A and B with same length n is
disA,B=i=0n1|AiBn1i|
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
T100
0m5000
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
找给定的字符串的两个子串,他们的距离定义为:disA,B=i=0n1|AiBn1i|。求使得距离小于等于m

的最长子串。

思路:答案肯定具有二分性质的,所以考虑二分枚举答案,然后考虑怎么求得子串的距离。

我们可以知道,对于一个字符串:abcdefedcb。第一个字符串从前往后,第二个字符串从后往前做枚举,例如:

abc匹配dcb那么就是:

abc

bcd(相同位置相减)

那么下一次,前后同时移动一个位置:

bcd

cde

那么前后之后一个位置不同,其他位置相同,那么我们就可以在o(1)时间内求得这两个串的dis。

具体实现看代码,有两次双重循环。

这样代码就是n*n*log(n),实际复杂度在n*n以内(反正跑了1600ms+)

#include <iostream>
#include<stdio.h>
#include<string.h>
#include<algorithm>
#define siz 5005
const int maxn = 5000;
typedef long long LL;
using namespace std;
int m,len;
char str[maxn+15];
bool ok(int l)
{
    int cot = 0,s,t;
    for(int i=1;i+l*2-1<=len;i++)
    {
        cot= 0 ;
        for(int j=0;j<l;j++) cot+=abs(str[i+j]-str[len-j]);
        if(cot<=m) return true;
        s = i+1, t = len-1;
        while(t-s+1>=l*2)
        {
            cot = cot + abs(str[s+l-1]-str[t-l+1]) - abs(str[s-1]-str[t+1]);
            if(cot<=m) return true;
            s++,t--;
        }
    }
    cot = 0;
    for(int i=len;i>=l*2;i--)
    {
        cot = 0;
        for(int j=0;j<l;j++) cot+=abs(str[i-j]-str[j+1]);
        if(cot<=m) return true;
        s = i-1,t = 2;
        while(s-t+1>=l*2)
        {
            cot = cot - abs(str[s+1]-str[t-1]) + abs(str[s-l+1]-str[t+l-1]);
            if(cot<=m) return true;
            s--,t++;
        }
    }
    return false;
}
void solve()
{
    int l=0,r=len/2+1,mid,ans=0;
    while(r-l>1)
    {
        mid = (l+r)>>1;
        if(ok(mid)) l = mid,ans = max(ans,mid);
        else r = mid;
    }
    printf("%d\n",ans);
}
int main()
{
    int T;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d",&m);
        scanf("%s",str+1);
        len =  strlen(str+1);
        solve();
    }
    return 0;
}


abcdef

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值