HDU 5317 RGCDQ(思维)

RGCDQ

Time Limit: 6000/3000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 3655    Accepted Submission(s): 1367


 

Problem Description

Mr. Hdu is interested in Greatest Common Divisor (GCD). He wants to find more and more interesting things about GCD. Today He comes up with Range Greatest Common Divisor Query (RGCDQ). What’s RGCDQ? Please let me explain it to you gradually. For a positive integer x, F(x) indicates the number of kind of prime factor of x. For example F(2)=1. F(10)=2, because 10=2*5. F(12)=2, because 12=2*2*3, there are two kinds of prime factor. For each query, we will get an interval [L, R], Hdu wants to know maxGCD(F(i),F(j)) (L≤i<j≤R)

 

Input

There are multiple queries. In the first line of the input file there is an integer T indicates the number of queries.
In the next T lines, each line contains L, R which is mentioned above.

All input items are integers.
1<= T <= 1000000
2<=L < R<=1000000

 

Output

For each query,output the answer in a single line. 
See the sample for more details.

 

Sample Input

 

2 2 3 3 5

 

Sample Output

 

1 1

题意:

定义f(i)为i的质因子个数,给定i,j求区间最大gcd(f(i),f(j))。

思路:肯定是先筛素数啦,然后再算出每个数的f(i),接下来就是关键:

发现1000000以内质因子最多的也就是7,于是我们维护sum[i][8]表示前i个数质因子为1234567的共有多少个。

然后求[l,r]的最大gcd时,用一个数组a[j]=sum[r][j]-sum[l-1][j];(j=1,2,3,4,5,6,7),然后暴力求最大gcd即可。注意a[j]>=2时最大gcd可能是j。

代码:

#include<bits/stdc++.h>
#define ll long long
#define inf 0x3f3f3f3f
using namespace std;
const int maxn=1000100;
int n,m,q,tot,tot2;
int ans,cnt,tmp;
bool b[maxn];
int l,r,g,k;
int f[maxn],c[maxn][7];
void init()
{
    memset(b,0,sizeof(b));
    memset(f,0,sizeof(f));
    n=0;
    for(int i=2;i<=1000000;i++)
    {
        for(int j=2;j*i<=1000000;j++)
        {
            b[i*j]=1;
        }
    }
    for(int i=2;i<=1000000;i++)
    if(!b[i]){
        for(int j=1;j*i<=1000000;j++)
        {
            f[i*j]++;
        }
    }
    for(int i=1;i<=1000000;i++)
    for(int j=1;j<=7;j++)
    {
        c[i][j]=c[i-1][j];
        if(f[i]==j) c[i][j]++;
    }
}
int gcd(int a,int b)
{
   return b>0?gcd(b,a%b):a;
}
int main()
{
    init();
    int T,cas=1;
    scanf("%d",&T);
    while(T--){
        int l,r;
        scanf("%d %d",&l,&r);
        ans=1;
        for(int i=7;i>=1;i--)
        {
            f[i]=c[r][i]-c[l-1][i];
            if(f[i]>=2){ans=max(ans,i);}
        }
        for(int i=1;i<=7;i++)
        for(int j=1;j<=7;j++)
        if(i!=j&&f[i]&&f[j])
        ans=max(ans,gcd(i,j));
        printf("%d\n",ans);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/lsd20164388/article/details/81129597