Kirinriki(HDU 6103)

来源:互联网 发布:c语言初级程序 编辑:程序博客网 时间:2024/05/16 21:14

Kirinriki

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


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
Hint
[0, 4] abcde[5, 9] fedcbThe distance between them is abs('a' - 'b') + abs('b' - 'c') + abs('c' - 'd') + abs('d' - 'e') + abs('e' - 'f') = 5
 

//题意

PS:Kirinriki:麒麟奇,神奇宝贝。

一个字符串里找两个长度相同的子串,两个子串不能重叠,两个子串的距离必须<=m,m已知,距离的算法题目里也已给出,问子串的最大长度。

//官方题解

两个不重合的子串向中心一起延长会形成奇偶长度两种合串。

枚举一下中心向外延伸,如果和超过了阈值弹掉中心处的位置。

双指针维护。

O(n^{2})时间复杂度 O(n2)

简单来说,就是从两端往里缩进,如果>m了,删掉最前面的那对点继续往里缩进,字符串正序逆序各来一次,相当于把所有情况枚举了一遍,但暴力的比较巧妙。


#include <iostream>#include <cstdio>#include <cstring>#include <string>#include <cmath>#include <algorithm>using namespace std;const int MAX = 5000 + 100;int m, len;char str1[MAX];char str2[MAX];//尺取法int work(char *str){int ans = 0;for (int i = len - 1; i >= 0; i--){int cnt = (i + 1) / 2 - 1;int sum = 0, num = 0, pos = 0;for (int j = 0; j <= cnt; j++){sum += abs(str[j] - str[i - j]);if (sum > m){sum -= abs(str[pos] - str[i - pos]);sum -= abs(str[j] - str[i - j]);num--;pos++;j--;}else{num++;ans = max(ans, num);}}}return ans;}int main(){int T;scanf("%d", &T);while (T--){scanf("%d", &m);scanf("%s", str1);len = strlen(str1);for (int i = 0; i < len; i++){str2[i] = str1[len - i - 1];}int res = 0;res = max(res, work(str1));res = max(res, work(str2));printf("%d\n", res);}return 0;}




原创粉丝点击