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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值