You are given an array A of integers of size N. You will be given Q queries where each query is represented by two integers L, R. You have to find the gcd(Greatest Common Divisor) of the array after excluding the part from range L to R inclusive (1 Based indexing). You are guaranteed that after excluding the part of the array
remaining array is non empty.
Input
First line of input contains an integer T denoting number of test cases.
For each test case, first line will contain two space separated integers N, Q.
Next line contains N space separated integers denoting array A.
For next Q lines, each line will contain a query denoted by two space separated integers L, R.
Output
For each query, print a single integer representing the answer of that query.
Constraints
Subtask #1: 40 points
2 ≤ T, N ≤ 100, 1 ≤ Q ≤ N, 1 ≤ A[i] ≤ 105
1 ≤ L, R ≤ N and L ≤ R
Subtask #2: 60 points
2 ≤ T, N ≤ 105, 1 ≤ Q ≤ N, 1 ≤ A[i] ≤ 105
1 ≤ L, R ≤ N and L ≤ R
Sum of N over all the test cases will be less than or equal to 106.
Example
Input:
1
3 3
2 6 9
1 1
2 2
2 3
Output:
3
1
2
Explanation
For first query, the remaining part of array will be (6, 9), so answer is 3. For second query, the remaining part of array will be (2, 9), so answer is 1. For third query, the remaining part of array will be (2), so answer is 2.
Warning : Large IO(input output), please use faster method for IO.
解题思路:
利用GCD函数来求剩余元素的最大公约数
int GCD(int a,int b)
{
return b==0? a:GCD(b,a%b);
}
需要考虑剩余元素的读入,不然会运行超时
第一次打法(运行超时):
#include<stdio.h>
int a[1000005];
int GCD(int a,int b)
{
return b==0? a:GCD(b,a%b);
}
int main()
{
int n;
scanf("%d",&n);
int N,Q,i,j,L,R,k,q,l,r;
for(i=0;i<n;i++)
{
scanf("%d%d",&N,&Q);
for(j=1;j<=N;j++)
{
scanf("%d",&a[j]);
}
for(j=0;j<Q;j++)
{
scanf("%d%d",&L,&R);
if(L!=1&&R!=1)
q=a[1];
if(L==1&&R!=N)
q=a[N];
if(L==1&&R==N)
q=1;
for(k=1;k<=N;k++)
{
if(k<=R&&k>=L){
}else
{
q=GCD(q,a[k]);
if(q==1)
break;
}
}
printf("%d\n",q);
}
}
}
第二次打的时候考虑到当输入测试数据个数N很大时,第一次的打法每测试一次都要将剩余元素进行GCD,代码运行时间就会很长。想了很久,利用打表的方法,将从前往后的GCD存在数组a里,将从后往前的GCD存在数组b里。最后求a[L-1]和b[R+1]的最大公约数即可。
for(j=2;j<=N;j++)
{
scanf("%d",&a[j]);
b[j]=a[j];
a[j]=GCD(a[j],a[j-1]);
}
for(j=N-1;j>=1;j--)
{
b[j]=GCD(b[j],b[j+1]);
}
完整代码:
#include<stdio.h>
int a[100005],b[100005];
int GCD(int a,int b)
{
return b==0? a:GCD(b,a%b);
}
int main()
{
int n;
scanf("%d",&n);
int N,Q,i,j,L,R,k,q,l,r;
for(i=0;i<n;i++)
{
scanf("%d%d",&N,&Q);
scanf("%d",&q);
a[1]=b[1]=q;
for(j=2;j<=N;j++)
{
scanf("%d",&a[j]);
b[j]=a[j];
a[j]=GCD(a[j],a[j-1]);
}
for(j=N-1;j>=1;j--)
{
b[j]=GCD(b[j],b[j+1]);
}
for(j=1;j<=Q;j++)
{
scanf("%d%d",&L,&R);
if(L==1) //特判
printf("%d\n",b[R+1]);
else if(R==N)
printf("%d\n",a[L-1]);
else
printf("%d\n",GCD(a[L-1],b[R+1]));
}
}
}