HDU 6103 Kirinriki

来源:互联网 发布:python可以做界面吗 编辑:程序博客网 时间:2024/06/05 13:34

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;}
原创粉丝点击