1138A A. Sushi for Two

Arkady invited Anna for a dinner to a sushi restaurant. The restaurant is a bit unusual: it offers n pieces of sushi aligned in a row, and a customer has to choose a continuous subsegment of these sushi to buy.

The pieces of sushi are of two types: either with tuna or with eel. Let’s denote the type of the i-th from the left sushi as ti, where ti=1 means it is with tuna, and ti=2 means it is with eel.

Arkady does not like tuna, Anna does not like eel. Arkady wants to choose such a continuous subsegment of sushi that it has equal number of sushi of each type and each half of the subsegment has only sushi of one type. For example, subsegment [2,2,2,1,1,1] is valid, but subsegment [1,2,1,2,1,2] is not, because both halves contain both types of sushi.

Find the length of the longest continuous subsegment of sushi Arkady can buy.

Input
The first line contains a single integer n (2≤n≤100000) — the number of pieces of sushi.

The second line contains n integers t1, t2, …, tn (ti=1, denoting a sushi with tuna or ti=2, denoting a sushi with eel), representing the types of sushi from left to right.

It is guaranteed that there is at least one piece of sushi of each type. Note that it means that there is at least one valid continuous segment.

Output
Print a single integer — the maximum length of a valid continuous segment.

Examples
input

7
2 2 2 1 1 2 2
output
4
input
6
1 2 1 2 1 2
output
2
input
9
2 2 1 1 1 2 2 2 2
output
6
Note
In the first example Arkady can choose the subsegment [2,2,1,1] or the subsegment [1,1,2,2] with length 4.

In the second example there is no way but to choose one of the subsegments [2,1] or [1,2] with length 2.

In the third example Arkady’s best choice is the subsegment [1,1,1,2,2,2].
题目大意: Arkady 和 Anna去寿司店吃晚饭,提供n个寿司,共两种口味(口味类型用1和2表示),顾客要从中选出连续的子序列作为晚餐,但其两人各喜欢其中一种口味,于是他们要从中选出最长连续的两种口味序列,即每人的寿司数量相同,且每个人的序列是连续的(eg: 1 2 ; 1 1 2 2; 2 2 1 1;…),求两人选取的这个序列的最长长度是多少。
思路: 首先其答案一定是偶数,且序列为对称相反的数,在循环中利用两个数记录当前数组下标和下一个数组下标,并判断两数是否不相等,不相等时左边的下标往左移一个单位长度,右边的下标往右移一个单位长度,同时判断左半部分的数是否相等(因为两边都是连续的,考虑一边的情况即可),再不断更新最长子序列长度,详情看代码。

#include <iostream>
#include <algorithm>
using namespace std;
int main() {
	int n, ans, maxn  = 0, a[100005];
	scanf("%d", &n);
	for(int i = 0; i < n; i++) {
		scanf("%d", &a[i]);
	}
	for(int i = 0; i < n; i++) {
		int x = i; // 取当前元素下标 
		int y = i + 1;  // 取下一个元素下标 
		int k = a[x]; // 标记是否是连续相同的序列 
		ans = 0; // 每次初始化为0,进行下一轮统计 
		while(a[x] != a[y] && a[x] == k && x >= 0 && y < n) { // 判断当前两数值是否相等且左半部分的数是否都一致 
			k = a[x]; // 更新数值 
			x--; // 左下标往左移 
			y++; // 右下标往左移
			ans += 2; // 长度加2 
		}
		if(ans > maxn)	maxn = ans; // 更新最大长度值 
	}
	printf("%d\n", maxn);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/dream_it_/article/details/88715248