HDU6103 Kirinriki(区间dp+二分)

Kirinriki

传送门1
传送门2
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


题意

给出字符串 s ,在里面取两段长度相同并且不重叠的子串,并且满足对应位置 ASCII 码差值的绝对值的和不超过 m ,求子串最长长度。

分析

定义dp[i][j]表示A串为区间 [i,i+j12] ,B串为区间 [i+j2+1,j] 的值。
然后二分答案,枚举长度mid

只要满足dp[i-mid+1][j+mid]-dp[i+1][j]<=m就表示长度为mid时可以.

CODE

#include<cstdio>
#include<cstring>
#define N 5005
#define FOR(i,a,b) for(int i=(a),i##_END_=(b);i<=i##_END_;i++)
char s[N];
unsigned short dp[N][N];//开int会炸
int len,m;
inline int abs(int x) {return x>0?x:-x;}
bool check(int mid) {
    FOR(i,mid,len-mid)FOR(j,i,len-mid)
        if(dp[i-mid+1][j+mid]-dp[i+1][j]<=m)
            return 1;
    return 0;
}
int main() {
    int t;
    scanf("%d",&t);
    while(t--) {
        scanf("%d%s",&m,s+1);
        len=strlen(s+1);
        FOR(i,1,len)dp[i][i]=0;
        FOR(k,2,len)FOR(i,1,len-k+1) {
            int j=i+k-1;
            dp[i][j]=dp[i+1][j-1]+abs(s[i]-s[j]);
        }
        int L=1,R=len/2,mid,ans=0;
        while(L<=R) {
            mid=(L+R)>>1;
            if(check(mid))ans=mid,L=mid+1;
            else R=mid-1;
        }
        printf("%d\n",ans);
    }
    return 0;
}
发布了34 篇原创文章 · 获赞 44 · 访问量 5092

猜你喜欢

转载自blog.csdn.net/zzyyyl/article/details/78379085