HDU 6103 Kirinriki

We define the distance of two strings A and B with same length n is
disA,B=n1i=0|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
T≤100
0≤m≤5000
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
题意:
就是让你找两个长度相同的子串,在上面提到的dis不超过m的情况下的长度的最大值。
思路:一开始怎么想怎么都想不出来 n2 的做法,总是带着个串的长度。然后思维也僵化的很严重,到最后也不知道怎么做。这个题我们从答案来入手,我们所获得的最优的解的情况,一定存在一个中间位置,没错,那么我们为什么不去枚举那个中间位置呢。确实想不到呢。。。。因为当时根本不能理解这个为什么得出来的是对的。
这个官方题解说题目名字给提示,表示根本不认识这题目是啥啊。

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <queue>
#include <cmath>
#include <stdlib.h>
using namespace std;
typedef long long LL;
const int MAXN = 5000+10;
int ans, m, len;
char s[MAXN];

int main()
{
    int t;
    scanf("%d", &t);
    while(t--)
    {
        scanf("%d", &m);
        scanf("%s", s);
        len = strlen(s);
        ans = 0;
        //枚举中间的对称点,真实存在
        for(int i = 1; i < len; ++i)
        {
            int l1 = i-1,r1 = l1;
            int l2 = i+1,r2 = l2;
            int sum = 0;
            while(l1 >= 0 && l2 < len)
            {
                sum += abs(s[l1] - s[l2]);
                while(sum > m)sum -= abs(s[r1--] - s[r2++]);
                ans = max(ans,r1 - l1 + 1);
                //printf("i:%d r1:%d l1:%d ans:%d\n",i,r1,l1,ans);
                l1--;
                l2++;
            }
        }
        //枚举中间的对称空隙(点不存在)
        for(int i = 0; i < len; ++i)
        {
            int l1 = i,r1 = l1;
            int l2 = i+1,r2 = l2;
            int sum = 0;
            while(l1 >= 0 && l2 < len)
            {
                sum += abs(s[l1] - s[l2]);
                while(sum > m)sum -= abs(s[r1--] - s[r2++]);
                ans = max(ans,r1 - l1 + 1);
                l1--;
                l2++;
            }
        }
        printf("%d\n", ans);
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值