hdu--6103--Kirinriki

来源:互联网 发布:网络打印机ip地址 编辑:程序博客网 时间:2024/06/05 15:05

Kirinriki

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


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
15abcdefedcb
 

Sample Output
5


题意 :

给出一串字符串,从中选出两个不重叠的子串,使得两个子串满足距离和 <= m 的最长字符串长度,A,B 串中的字符距离计算为disA,B=i=0n1|AiBn1i||Ai−Bn−1−i|为两个字符之间的asc码的差的绝对值。

解题思路:

这道题是用暴力枚举解的,关键是怎么用暴力,才能不超时,这就需要找到一种可以快速的且不重复的枚举所有情况的暴力方法。观察字符串可以看出,任意的两个不重复的子串在原字符串中,都可以找到唯一的一个对称轴,当我们把所有的对称轴都枚举一遍,就能实现把所有的情况枚举一遍,枚举对称轴比较容易实现,且不容易重复,对于每个对称轴,我们再用尺取法去寻找关于该中心轴对称的两个dis <= m的最长子串

代码:

 C++ Code 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include<bits/stdc++.h>
using namespace std;
char s[5005];
int main()
{
    int T;
    scanf("%d", &T);
    while(T--)
    {
        int m;
        scanf("%d %s", &m, s + 1);
        int len = strlen(s + 1);
        int l1, r1, l2, r2, tmp;
        int ans = 0;
        for(int i = 1; i <= len; i++)
        {
            ///以第i - 1个字符和第i个字符之间的空为对称轴
            l1 = r1 = i - 1;
            l2 = r2 = i;
            tmp = 0;
            while(l1 >= 1 && r2 <= len)
            {
                tmp += abs(s[l1] - s[r2]);
                while(tmp > m && l1 <= r1 && l2 <= r2)
                    tmp -= abs(s[r1--] - s[l2++]);
                if(tmp <= m)
                    ans = max(ans, r1 - l1 + 1);
                l1--;
                r2++;
            }
            ///以第i个字符为对称轴
            l1 = r1 = i - 1;
            l2 = r2 = i + 1;
            tmp = 0;
            while(l1 >= 1 && r2 <= len)
            {
                tmp += abs(s[l1] - s[r2]);
                while(tmp > m && l1 <= r1 && l2 <= r2)
                    tmp -= abs(s[r1--] - s[l2++]);
                if(tmp <= m)
                    ans = max(ans, r1 - l1 + 1);
                l1--;
                r2++;
            }
        }
        printf("%d\n", ans);
    }
    return 0;
}