HDU6103 Kirinriki-dp+二分 - 2017多校联盟6 第8题

Kirinriki

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


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
 

Source
 8


/*
题意
定义两个字符串的距离dis = Σ| Ai - Bn-1-i |
给你一个字符串s, 问你s子串中dis<=m的最大长度是多少,两个子串不能有公共部分

题解
二分长度,因为不能有重叠部分那么最长就是len/2.
如果在当前长度下存在一对子串满足dis<=m那么更新ans并更新区间
问题是判断dis<=m如果直接暴力会超时。这里使用数组dp
dp[i][j]表示从区间[i,j]以终点分割的两个子串的dis
那么任意起点为i和j长度为l的两个子串的dis = dp[i][j+l-1] - dp[i+1][j-1]
dp数组预处理:dp[i][j] = dp[i+1][j-1] + abs(s[i]-s[j])
dp使用int 会空间超限,使用short会超范围。使用unsigned short刚好
复杂度n^2logn
*/
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
 using namespace std;

const int maxn = 5000+10;

int m;
char s[maxn];
unsigned short dp[maxn][maxn];
int len;
bool ok(int l){
    for(int i = 0;i<len;++i){
        for(int j = i+l;j<len;++j){
            if(j+l-1 >= len) break;
            if(dp[i][j+l-1] - dp[i+l][j-1]<=m)
                return true;
        }
    }
    return false;
}

int main()
{
    int t;
    scanf("%d", &t);

    while (t > 0){
        t--;
        scanf("%d", &m);
        scanf("%s",s);
        len = strlen(s);
        ///预处理dp
        for(int l = 1; l <=len; ++l){///区间长度
            for(int i = 0; i < len; ++i){
                int j = i+l-1;
                if(j>=len) continue;
                dp[i][j] = dp[i+1][j-1] + abs(s[i]-s[j]);
            }
        }

        int l = 1;
        int r = len/2;
        int ans = 0;
        while(l<=r){
            int mid = (l+r)>>1;
            if(ok(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、付费专栏及课程。

余额充值