Hdu 6103 Kirinriki【区间DP+二分】

来源:互联网 发布:windows正版验证原理 编辑:程序博客网 时间:2024/06/03 23:50

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
15abcdefedcb
 

Sample Output
5
Hint
[0, 4] abcde[5, 9] fedcbThe 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);    }}









原创粉丝点击