1571: Subarray GCD
Time Limit: 1 Sec Memory Limit: 128 MBSubmit: 37 Solved: 22
[ Submit][ Status][ Web Board]
Description
Given an array A1,A2...AN, you have to print the size of the largest contiguous subarray such that
GCD of all integers in that subarray is 1.
Formally,
For a subarray Ai,Ai+1...Aj where 1 ≤ i < j ≤ N to be valid: GCD(Ai,Ai+1...Aj) should be 1. You have to print the size of the largest valid subarray.
If no valid subarray exists, output -1.
Note:A single element is not considered as a subarray according to the definition of this problem.
Input
First line contains T, the number of testcases. Each testcase consists of N in one line followed by Nintegers in the next line.
Constraints
- 1 ≤ T ≤ 10
- 2 ≤ N ≤ 105
- 1 ≤ Ai ≤ 105
Output
For each testcase, print the required answer in one line.
Sample Input
2
2
7 2
3
2 2 4
Sample Output
2
-1
【解析】
此题就是要我们求最大公约数为1的最长子序列,其实我们这个时候想啊1是所以数的公约数,那么我们如果有一个序列
比如说1,2它们的最大公约数是为1,不管你加什么数,多少个数,它们的最大公约数只能是l。所以这道题其实只有两个
解,一个要么是整个序列的长度一个要么是-1,那我们怎么求它们的公共最大公约数呢,比如我们有三个数2和4和8,它们
的最大公约数是2,然后2再和8比较最大公约数也是2,所以就是这么来的不断的去求。如果这个时候第三个数不是8了,是
7,那么此时最大公约数就是1了。1也是前面两个数的公约数。
#include<cstdio>
#include<algorithm>
#include<iostream>
#include<map>
#include<cstring>
using namespace std;
int gcd(int a,int b)
{
int temp;
while(b)
{
temp=a%b;
a=b;
b=temp;
}
return a;
}
int main()
{
int t,n,m,i,k;
scanf("%d",&t);
while(t--)
{
k=0;
scanf("%d",&n);
scanf("%d",&k);
for(i=0;i<n-1;i++)
{
scanf("%d",&m);
k=gcd(k,m);
}
if(k==1)
printf("%d\n",n);
else
printf("-1\n");
}
return 0;
}