您的位置:首页 > 运维架构

HDU 6103 17多校6 Kirinriki(双指针维护)

2017-08-11 10:53 211 查看
[align=left]Problem Description[/align]
We define the distance of two strings A and B with same length n is
disA,B=∑i=0n−1|Ai−Bn−1−i|
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.

[align=left]Input[/align]
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

[align=left]Output[/align]
For each test case output one interge denotes the answer : the maximum length of the substring.

[align=left]Sample Input[/align]

1
5
abcdefedcb

[align=left]Sample Output[/align]

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

启发博客:http://www.cnblogs.com/coded-ream/p/7343946.html
以下题解和题意摘自此博客

题目描述:


找两个不重叠的字符串A,B。 使得dis(A,B)<=m;





















































dis(A,B)=∑i=0n−1|Ai−Bn−1−i|。求最长的字符串长度。


思路:


官方题解,双指针维护。简单题。枚举对称中心。



双指针维护!!以后要搜超时就记这个!!

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<queue>
#include<map>
#include<vector>
#include<cmath>
#include<cstring>
using namespace std;
int m,ans,len;
char str[5005];

void solve(int x,int y)//x,y表示左右端点
{
int dis=0;
int l=0,r=0;//双指针,r记录的是两段各自的长度,l记录的是头尾各自缩进多少
while(x+r<y-r)
{
if(dis+abs(str[x+r]-str[y-r])<=m)
{
dis+=abs(str[x+r]-str[y-r]);
r++;
ans=max(ans,r-l);
}
else
{
dis-=abs(str[x+l]-str[y-l]);
l++;
}
}
}

int main()
{
int T;
scanf("%d",&T);
while(T--)
{
scanf("%d",&m);
cin>>str;
ans=0;
len=strlen(str);
for(int i=1;i<len;i++)
solve(0,i);//相当于枚举对称轴在前半段
for(int i=0;i<len-1;i++)
solve(i,len-1);//相当于枚举对称轴在后半段
printf("%d\n",ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: