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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章