解题报告 之 HDU5317 RGCDQ

20 篇文章 2 订阅

解题报告 之 HDU5317 RGCDQ


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   
 

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(x)为 x 的质因子的种类数,比如20=2*2*5,那么F(x)=2 。现在给出区间[L,R],问你该区间内中任意两个数的GCD的最大值是多少?

分析:首先不管是不是一开始就想到要怎么做,肯定要完成的是把每个数的F(x)求出来,这里很自然的想到了筛法。对于每个质数,它的每个倍数的质因子数都++。然后扫一遍之后就完成了F(x)的更新。筛法具体见相关文章一。

好筛完了F(x),那么怎么求最大的GCD呢,一开始发现肯定不能暴力来,所以纠结了一会儿。然后后来看调试发现F(x)的值全都是1,2,3,4。。。这种小数,然后统计出来一看最大的F(x)才只有7。那么这个问题就迎刃而解了,直接扫一遍更新到R为止每种F(x)有多少个。然后区间给定之后依次判断各种情形即可。

上代码:
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;

typedef long long ll;
const int MAXN = 1e6 + 10;

int isprime[MAXN];
int f[MAXN];
int dis[MAXN][8];

void ini()
{
	memset( isprime, -1, sizeof isprime );
	memset( f, 0, sizeof f );
	memset( dis, 0, sizeof dis );

	for(int i = 2; i < MAXN; i++)
	{
		if(!isprime[i]) continue;
		for(int j = i; j < MAXN; j += i)
		{
			f[j]++;
			isprime[j] = 0;
		}
	}

	for(int i = 2; i < MAXN; i++)
	{
		for(int j = 1; j <= 7; j++)
		{
			dis[i][j] = dis[i - 1][j];
		}
		dis[i][f[i]]++;
	}

}

int main()
{
	ini();
	int kase;
	scanf( "%d", &kase );

	while(kase--)
	{
		int l, r;
		scanf( "%d%d", &l, &r );

		int ma = 0;
		for(int i = 7; i >= 2;i--)
		{
			if(dis[r][i] - dis[l - 1][i] >= 2) 
			{
				ma = i;
				break;
			}
		}

		if(dis[r][6] - dis[l - 1][6] >= 1 && dis[r][2] - dis[l - 1][2] >= 1)
		{
			ma = max( ma, 3 );
		}

		if(dis[r][6] - dis[l - 1][6] >= 1 && dis[r][3] - dis[l - 1][3] >= 1|| dis[r][4] - dis[l - 1][4] >= 1 && dis[r][2] - dis[l - 1][2] >= 1)
		{
			ma = max( ma, 2 );
		}

		ma = max( ma, 1 );
		printf( "%d\n", ma );

	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值