HDU 6103 Kirinriki —— 不重叠的字符串距离最小

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.
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
1
5
abcdefedcb
Sample Output
5

Hint
[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

题意:

给你一个字符串,让你求出距离不超过m的两个不重叠的最长子串,距离在上面有定义。

题解:

一开始想着二分,结果check函数写不出来,看了别人的代码发现这个想法很简单但是又很容易想不到。这两个串的中间字符只有偶数和奇数的情况,那么枚举每一个点作为对称的中点,两个字符串相隔偶数和奇数的情况。之后check就是尺取了。

#include<bits/stdc++.h>
using namespace std;
char s[5005];
int len,m,ans;
void check(int x,int y)
{
    int l=0,r=0,dis=0;
    while(y+r<len&&x-r>=0)
    {
        if(dis+abs(s[y+r]-s[x-r])<=m)
        {
            dis+=abs(s[y+r]-s[x-r]);
            ans=max(ans,r-l+1);
            r++;
        }
        else
        {
            dis-=abs(s[y+l]-s[x-l]);
            l++;
        }
    }
}
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d",&m);
        scanf("%s",s);
        len=strlen(s);
        ans=0;
        for(int i=0;i<len;i++)
            check(i-1,i+1),check(i,i+1);
        printf("%d\n",ans);
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值