HDU 6103 Kirinriki

来源:互联网 发布:淘宝手机直通车怎么找 编辑:程序博客网 时间:2024/06/05 03:37

题目

Kirinriki

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


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
 

题意


给一个字符串,求它的两个不重合的情况下计算的dis<m的时候求长度最大的子串,并输出长度


解题思路


第一次做的时候就单纯的交了个朴素, 然后超时了,又想到前缀和,一看是分开的绝对值又放弃了,做不出来在那里瞎逛游,在纸上做了推演,发现如果我把大区间都找出来,每一个大区间里面的小区间的和我就不用求了,因为大区间包括了小区间,我只要把所有的区间的可能性找出来就可以了,实际上只要找到所有的开始和结尾的组合就可以了。

 

#include<iostream>#include<cstring>#include<cstdio>#include<cmath>#include<algorithm>using namespace std;int sum1[5000+10];int sum2[5000+10];int main(){    int T;    scanf("%d",&T);    while(T--)    {        int flag=0;        int m;        int maxnlen=0;        scanf("%d",&m);        string str;        cin>>str;        int len=str.length();        for(int i=0;i<len;i++)        {            int last=len-1;            int first=0;            int cnt=0;            int tot=0;            for(int j=i;j<last;j++,last--)            {                sum2[cnt++]=abs(str[j]-str[last]);                tot+=abs(str[j]-str[last]);                if(tot>m)                   tot-=sum2[first++];                else                    maxnlen=max(maxnlen,j-i-first+1);            }            first=0;            cnt=0;            tot=0;            int tou=0;            for(int j=i;j>tou;j--,tou++)            {                sum1[cnt++]=abs(str[tou]-str[j]);                tot+=abs(str[tou]-str[j]);                 if(tot>m)                   tot-=sum1[first++];                 else                    maxnlen=max(maxnlen,tou-first+1);            }        }        printf("%d\n",maxnlen);    }    return 0;}




原创粉丝点击