【思维】hdu 6103 Kirinriki

本文介绍了一个关于字符串的问题,即如何寻找两个非重叠子串,使它们的定义距离小于等于给定值,并讨论了相应的解决算法。通过从中心向两端枚举的方法,实现了高效的求解。

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

Kirinriki

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 1792    Accepted Submission(s): 735


Problem Description
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
  
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和一个串,要在串中找到两个不会重叠长度相等并且长度尽量长的字串,使得定义的距离小于等于m;
思路:从中心向两端枚举,学弟画了一张图(抱大腿啊):


找每条斜线上的距离的和小于等于m的长度最长是多少,最后去最长即可;

代码:

#include<cstdio>
#include<cstring>
#include<iostream>
#include<cmath>
#include<algorithm>
using namespace std;

string s1,s2;
int s[5050],m;
int sum[5050];

int get_len(int n)  //尺取
{
    sum[0]=0;
    for(int i=1; i<=n; i++)
        sum[i]=sum[i-1]+s[i];

    int maxx=0,l=1,r=1;
    while(l<=r&&l<=n&&r<=n)
    {
        if(sum[r]-sum[l-1]<=m)
        {
            maxx=max(maxx,r-l+1);
            r++;
        }
        else
        {
            l++;
            if(l>r) //没加这句,wa晕
                r=l;
        }
    }
    return maxx;
}

int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        memset(s,0,sizeof(s));

        int max_len=0;
        scanf("%d",&m);
        cin>>s1;
        s2=s1;
        reverse(s2.begin(),s2.end());

        for(int i=0; i<(int)s1.size()-1; i++)
        {
            int len=(s2.size()-i)/2;
            if(max_len>=len) break;

            for(int j=0; j<len; j++)
                s[j+1]=abs(s1[i+j]-s2[j]);

            max_len=max(max_len,get_len(len));
        }

        for(int i=0; i<(int)s2.size()-1; i++)
        {
            int len=(s1.size()-i)/2;
            if(max_len>=len) break;

            for(int j=0; j<len; j++)
                s[j+1]=abs(s2[i+j]-s1[j]);

            max_len=max(max_len,get_len(len));
        }

        printf("%d\n",max_len);
    }
    return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值