Hdu 6103 Kirinriki【区间DP+二分】

351 篇文章 2 订阅
142 篇文章 0 订阅

Kirinriki

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


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,两个子串(连续子串)如果长度相等,其距离Dis为题干公式,问你最长的长度Len,使得我们可以找到两个子串长度为Len,其距离小于等于m。


思路:


设定Dp【i】【j】,表示前半段为A串,后半段为B串的AB字符串距离。

那么对于一个大区间Dp【i】【j】来讲,我们可以枚举出两个子字符串【L,R】,【LL,RR】(LL>R),那么两个字符串的距离就是Dp【i】【j】-Dp【R+1】【LL-1】;


预处理Dp数组,然后我们二分答案去check就行了。


Ac代码:

#include<stdio.h>
#include<iostream>
#include<string.h>
#include<algorithm>
using namespace std;
short dp[5005][5005];
char a[5005];
int m;
int Slove(int mid)
{
    int n=strlen(a);
    for(int l=0;l<n;l++)
    {
        int r=l+mid-1;
        if(r>=n)break;
        for(int L=r+1;L<n;L++)
        {
            int R=L+mid-1;
            if(R>=n)break;
            if(dp[l][R]-dp[r+1][L-1]<=m)return 1;
        }
    }
    return 0;
}
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d",&m);
        scanf("%s",a);
        int n=strlen(a);
        memset(dp,0,sizeof(dp));
        int ans=-1;
        for(int len=2;len<=n;len++)
        {
            for(int l=0;l<n;l++)
            {
                int r=l+len-1;
                if(r>=n)break;
                if(len==2)dp[l][r]=abs(a[l]-a[r]);
                else
                dp[l][r]=dp[l+1][r-1]+abs(a[l]-a[r]);
            }
        }
        int l=0;
        int r=strlen(a);
        while(r-l>=0)
        {
            int mid=(l+r)/2;
            if(Slove(mid)==1)
            {
                ans=max(ans,mid);
                l=mid+1;
            }
            else r=mid-1;
        }
        printf("%d\n",ans);
    }
}









  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值