Codeforces Round #765被橄榄了。但B与C两题都刚好处在有思路而没解出来的难度,是很好的学习机会。
题目描述
Elementary Particles
Martians(火星人) are actively engaged(吸引,卷入) in interplanetary trade. Olymp City, the Martian city known for its spaceport, has become a place where goods from all the corners of our Galaxy come. To deliver even more freight(货物;运费) from faraway planets, Martians need fast spaceships.
A group of scientists conducts experiments to build a fast engine for the new spaceship. In the current experiment, there are
Denote
Note that the subsegments can be equal as sequences but still considered different. For example, consider the sequence (1 1 1 1 1) and two of its subsegments: one with
The scientists want to conduct(指导;引导;指挥) a reaction(反应) to get two different subsegments of the same length. Denote this length
The longer are harmonious subsegments, the more chances for the scientists to design a fast engine. So, they asked you to calculate the maximal possible length of harmonious pair made of different subsegments.
Input
The first line contains an integer
The first line contains an integer
The second line contains
It is guaranteed that the sum of
Output
For each test, print a single integer, maximal possible length of harmonious pair made of different subsegments. If such pair does not exist, print
Example
input: 1
2
3
4
5
6
7
8
94
7
3 1 5 2 1 3 4
6
1 1 1 1 1 1
6
1 4 2 8 5 7
2
15 15
output: 1
2
3
44
5
-1
1
解释
给定一个序列,找出两个连续子序列,满足:
- 两个子序列的在原序列中的位置不同,可以重叠但不能相等。
- 两个子序列至少有一个相同位置的元素相同。相同位置可以理解为数组下标,即要求至少存在一个
i,使得a[i]=b[i]成立。 - 两个子序列长度相等,且为所有符合要求的子序列组中最长的。
若存在这个的子序列组,输出它的长度。否则输出
思路
暴力
遍历所有子序列,并比对它们是否符合条件。由于长度是相等的,对于每种可能的长度只要确定起点就确定了终点。因此遍历时间复杂度为:
此外还得对每种遍历结果进行比对,时间复杂度
贪心
稍作思考,可以发现本题中只有序列起点会影响是否符合条件。因此可以使用下面的方式,逐步位移来比对序列,一但出现相同位置相同元素,则两序列重叠部分即为最长的序列组。

此时时间复杂度就降低至:位移
这里发现实际上我们的要求就是通过最短的位移将一对相同的元素对上。那只要找到原序列中最短相同元素对就可以了。位移后的长度损失为两元素间距,侧最长序列组长度为
找最短相同元素对需要为map记录下每个元素的最小元素对,然后只要一次搜索即可。时间复杂度为
本题由于空间够大,可以将map换成数组,将时间复杂度降低到
代码实现
1 |
|