Kirinriki(HDU 6103)

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

// 题意

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;
}




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值