ACM-Sushi

2019.7.24


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


我的思路:

用一个一维数组a存储寿司的种类,再另开一个f数组,用一个for循环把a数组遍历一遍,如果第i个和第i+1个数不同,就把a数组该元素的下标加一标记进f数组里;再用一个for循环计算f数组里相邻两项元素的差值,将最大的差值存入一个变量max里面,最后输出两倍max即为所求。


#include <iostream>
using namespace std;
int main()
{
    int i,n,l1,l2;
    int a[100005]={0};
    int f[100005]; 
    f[0]=0;  //用来计算第一个输入的寿司种类的个数
    cin >> n;
    int max=-1, j=1;
    int m;
    for(i=0; i<n; i++)
    {
        cin >> a[i];
    }
    
    for(i=0; i<n-1; i++)
    {
        if(a[i] != a[i+1])
        {
            f[j]=i+1;
            j++;
        }
        f[j]=n;
    }
    
    if(j>1)
    {
        for(int i=1; i<j; i++)
        {
            l1=f[i]-f[i-1];
            l2=f[i+1]-f[i];
            m = (l1>=l2)?l2:l1;
            if(m>max)
                max=m;
        }
        cout << max*2;
    }
    else
        cout << "0";
    return 0;
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,864评论 0 10
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 11,165评论 0 23
  • 小脸羞羞羽内藏。 心事也随波浪起, 悠悠梦里寻新娘。
    太阳_6539阅读 140评论 0 2
  • 我自己说出来要学费这件事情。 我没有在脑子里考虑。 或者说没有像以前那样深思熟虑,只是觉得应该告诉我领导实际情况而...
    lygly9阅读 281评论 0 0
  • 小时候有个数学题,讲得是如何有效时间里做多件事情,如何最大化的做事情,我跟你讲坚持三十分钟只做一件事,扯蛋吧。 不...
    风中燕子阅读 699评论 0 5

友情链接更多精彩内容