CodeChef Little Elephant and Balance

Given an array A1,A2...AN, you have to print the size of the largest contiguous subarray such that
LCM of all integers in that subarray is equal to the product of all integers in that subarray.

Formally,
For a subarray Ai,Ai+1...Aj where 1 ≤ i < j ≤ N to be valid: LCM(Ai,Ai+1...Aj) should be equal to Ai*Ai+1*...*Aj. You have to print the size of the largest valid subarray.

If no subarray satisfies output -1.

Note:A single element is not considered a subarray according to definition in this problem.

Input

First line contains T, the number of testcases. Each testcase consists of N in one line followed by N integers in next line.

Output

For each testcase, print the required answer in one line.

Constraints

  • 1T50
  • 2N105
  • 1Ai106

Example

Input:
3
2
7 2
4
2 2 3 4
3
2 2 4

Output:
2
2
-1

Explanation

Example case 1.LCM(2,7)=2*7. Therefore, subarray A1 to A2 satisfies.

Example case 2.The subarrays A2 to A3 and A3 to A4 are the maximum size possible.

Example case 3.No subarray will satisfy.

Warning: Use fast input/output. Large input files. Solutions may not pass in slower languages.

Update: Time limit for python=10s

 

给定序列, 求最长连续序列使得 lcm( Ax, ..... Ay ) = Ax*Ax+1*....*Ay .

满足要求的时候 , Ax ~ Ay 这些数要符合, 他们的质因子没有重复。

NlogN预处理质因子,dp出那个最右边的位置即可更新出答案 。~

#include <bits/stdc++.h>
using namespace std;
const int N = 100010;
const int M = 1000010;
int n,e[N],pos[N],ans[N],to[M],f[M];
bool not_pri[M] ;

void init() {
    int tot = 0 ;
    for( int i = 2 ; i < M ; ++i ) if( !not_pri[i] ) {
        to[i] = ++tot; f[i] = i;
        for( int j = i + i ; j < M ; j += i ){
            not_pri[j] = true ; f[j] = i;
        }
    }
}

int Work( int num , int idx ) {
    int res = 0 ;
    while( num > 1 ){
        int tmp = f[num];
        if( pos[ to[tmp] ] ) res = max( res , pos[to[tmp]] );
        pos[ to[tmp] ] = idx ;
        while( num % tmp == 0 ) num /= tmp;
    }
    return res ;
}

void Run() {
    scanf("%d",&n);
    for( int i = 1 ; i <= n ; ++i ) scanf("%d",&e[i]);
    memset( pos , 0 , sizeof pos );
    for( int i = 1 ; i <= n ; ++i ) {
        ans[i] = max( ans[i-1] , Work( e[i] , i ) );
    }
    int res = 0 ;
    for( int i = 1 ; i <= n ; ++i ) res = max( res , i - ans[i] );
    if( res <= 1 ) puts("-1");
    else printf("%d\n",res);
}

int main()
{
//    freopen("in.txt","r",stdin);
    init();
    int _ , cas = 1 ;
    scanf("%d",&_);
    while(_--)Run();
}
View Code

 

转载于:https://www.cnblogs.com/hlmark/p/4296786.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值