HDU 6103 Kirinriki(尺取)

19 篇文章 0 订阅

Description

定义两个长度均为 n 的字符串A B 的距离为disA,B=i=0n1|AiBn1i|,给出一个字符串 S ,问S的满足距离小于 m 的两个等长不相交子串的长度最大值

Input

第一行一整数T表示用例组数,每组用例首先输入一整数 m 表示对S的子串距离的限制,之后输入一个只有小写字母的字符串 S (T100,0m5000,2|S|5000,|S|20000)

Output

输出 S 的满足距离小于m的两个等长不相交子串的长度最大值

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|SiSj| ,枚举 i+j 的和 k ,得到序列|SiSj|,i+j=k,问题变成求这个序列中满足和不超过 m 的最长子段,尺取法即可,总时间复杂度O(n2)

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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值