HDU 5371——Hotaru's problem——————【manacher处理回文】

Hotaru's problem

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 1765    Accepted Submission(s): 635


Problem Description
Hotaru Ichijou recently is addicated to math problems. Now she is playing with N-sequence.
Let's define N-sequence, which is composed with three parts and satisfied with the following condition:
1. the first part is the same as the thrid part,
2. the first part and the second part are symmetrical.
for example, the sequence 2,3,4,4,3,2,2,3,4 is a N-sequence, which the first part 2,3,4 is the same as the thrid part 2,3,4, the first part 2,3,4 and the second part 4,3,2 are symmetrical.

Give you n positive intergers, your task is to find the largest continuous sub-sequence, which is N-sequence.
 

 

Input
There are multiple test cases. The first line of input contains an integer T(T<=20), indicating the number of test cases. 

For each test case:

the first line of input contains a positive integer N(1<=N<=100000), the length of a given sequence

the second line includes N non-negative integers ,each interger is no larger than 109 , descripting a sequence.
 

 

Output
Each case contains only one line. Each line should start with “Case #i: ”,with i implying the case number, followed by a integer, the largest length of N-sequence.

We guarantee that the sum of all answers is less than 800000.
 

 

Sample Input
1
10
2 3 4 4 3 2 2 3 4 4
 

 

Sample Output
Case #1: 9
 
题目大意:给你t组数据,一个n,下面一行有n个数,问你能形成形如abccbaabc这样的序列长度最长是多少。
 
解题思路:先用manacher处理出来串的所有字符的回文半径。然后枚举第一段跟第二段回文位置i,从i+p[i]-->i进行枚举第二段跟第三段回文位置j。如果以j为回文中心的左端能小于等于i的位置,说明满足要求,更新结果。
 
#include<bits/stdc++.h>
using namespace std;
#define min(a,b) ((a)<(b)?(a):(b))
const int maxn=1e6;
int a[maxn],p[maxn];
void Manacher(int n){
    a[0]=-2;a[n+1]=-1;a[n+2]=-3;
    int mx=0,id=0;
    for(int i=1;i<=n+1;i++){    //需要处理到n+1
        if(i<mx){
            p[i]=min(p[id*2-i],mx-i);   //这里写的时候写成mx-id,SB了。
        }else{
            p[i]=1;
        }
        for(;a[i+p[i]]==a[i-p[i]];++p[i]);  //-2,-3防越界
        if(i+p[i]>mx){
            mx=p[i]+i;
            id=i;
        }
    }
    for(int i=1;i<=n+1;++i){
        --p[i];
    } 
}
int main(){
 //   freopen("1003.in","r",stdin);
//    freopen("OUTTTT.txt","w",stdout);
    int t,n,cnt=0;
    scanf("%d",&t);
    while(t--){
        scanf("%d",&n);
        for(int i=1;i<=2*n;i+=2){
            a[i]=-1;
            scanf("%d",&a[i+1]);
        }

        Manacher(2*n);
        int maxv=0,j;
        for(int i=1;i<=2*n;i+=2){           //2*n
            for(j=i+p[i];j-maxv>i;j-=2){ //逆序枚举。manacher算法保证j<=2*n+1 
                if(j-p[j]<=i){
                    maxv=j-i;
                    break;
                }
            }
        }
        maxv=3*(maxv/2);
        printf("Case #%d: %d\n",++cnt,maxv);
    }
    return 0;
}

  

posted @ 2015-08-13 11:07  tcgoshawk  阅读(301)  评论(0编辑  收藏  举报