No Pain No Game(树状数组)

Problem Description
Life is a game,and you lose it,so you suicide.
But you can not kill yourself before you solve this problem:
Given you a sequence of number a1, a2, ..., an.They are also a permutation of 1...n.
You need to answer some queries,each with the following format:
If we chose two number a,b (shouldn't be the same) from interval [l, r],what is the maximum gcd(a, b)? If there's no way to choose two distinct number(l=r) then the answer is zero.


Input
First line contains a number T(T <= 5),denote the number of test cases. Then follow T test cases. For each test cases,the first line contains a number n(1 <= n <= 50000). The second line contains n number a[sub]1[/sub], a[sub]2[/sub], ..., a[sub]n[/sub]. The third line contains a number Q(1 <= Q <= 50000) denoting the number of queries. Then Q lines follows,each lines contains two integer l, r(1 <= l <= r <= n),denote a query.


Output
For each test cases,for each query print the answer in one line.


Sample Input
1
10
8 2 4 9 5 7 10 6 1 3
5
2 10
2 4
6 9
1 4
7 10


Sample Output
5
2
2
4
3

题意:

给你个数字数字序列,然后m次查询,求区间[l,r]最大的两个数字的公因子。

思路:先预处理一下,求出每一个数字的因子,维护 c[j] 代表 [j,i] 出现 2 次以上的最大数。


#if 1
#include<bits/stdc++.h> 
using namespace std;
const int MAXX=5e4+5;
int c[MAXX],a[MAXX],ans[MAXX],pre[MAXX];
vector<int> factor[MAXX];
void pre_do() 
{
	for(int i=1; i<MAXX; i++)
	{
		for(int j=i; j<MAXX; j+=i)
		{
			factor[j].push_back(i);	
		}		
	}	  	
}
struct node
{
	int l,r,id;
	bool operator <(const node &a)const
	{
		return r<a.r;
	}
}nodes[MAXX];
int lowbit(int x)
{
	return x&(-x);
}

void add(int x,int v)
{
	for(; x>0; x-=lowbit(x))
	{
		c[x]=max(c[x],v);
	}
}
int sum(int x)
{
	int M=0;
	for(; x<MAXX; x+=lowbit(x))
	{
		M=max(c[x],M);
	}
	return M;
}


int main()
{
	
	ios::sync_with_stdio(false);
	pre_do();
	int t;
	cin>>t;
	while(t--)
	{
		memset(pre,0,sizeof(pre));
		memset(c,0,sizeof(c)); 
		int n,m;
		cin>>n;
		for(int i=1; i<=n; i++)
		{
			cin>>a[i];	
		}	
		cin>>m;
		for(int i=0; i<m; i++)
		{
			cin>>nodes[i].l>>nodes[i].r;
			nodes[i].id=i;
		}
		sort(nodes,nodes+m);
		int j=0;
		for(int i=1; i<=n&&j<m; i++)
		{
			int x=a[i];
			for(int k=0; k<(int)factor[x].size(); k++)
			{
				int val=factor[x][k];
				if(pre[val])
					add(pre[val],val);  //出现两次
				pre[val]=i;		
			}	
		
		
			while(j<m&& nodes[j].r==i)
			{
				ans[nodes[j].id]=sum(nodes[j].l);
				j++;
			}
		
		}
		for(int i=0; i<m; i++)
		{
			cout<<ans[i]<<endl;
		}
	}
	
	
}
#endif 
































  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值