codeforces475D CGCDSSQ

本文提供了一种使用 map 和数学方法解决 Codeforces 475D 题目的策略。通过枚举左端点并二分查找右端点,利用 map 存储所有可能的 gcd 值,有效地解决了区间 gcd 计算问题。

本文版权归ljh2000和博客园共有,欢迎转载,但须保留此声明,并给出原文链接,谢谢合作。

 

 

本文作者:ljh2000
作者博客:http://www.cnblogs.com/ljh2000-jump/
转载请注明出处,侵权必究,保留最终解释权!

 

题目链接:codeforces475D

正解:$map$+数学

解题报告:

  这题有两种做法,不过思想差不多。

  考虑以一个点为左端点的所有区间的不同的$gcd$最多只有$log$种,那么所有的区间的不同$gcd$不可能超过$nlogn$,那么我们就可以枚举左端点,然后二分下一个值的右端点,用$map$把答案存起来。

  不过我为了方便,写的是第二种方法,同样是从左往右做,每次把$map$中的所有值和当前数组合得到新的集合,用$map$存起来,这得到的是所有以当前节点为右端点的$ans$,用$map$存下所有$ans$方便最后查询即可。

 

//It is made by ljh2000
//有志者,事竟成,破釜沉舟,百二秦关终属楚;苦心人,天不负,卧薪尝胆,三千越甲可吞吴。
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <ctime>
#include <vector>
#include <queue>
#include <map>
#include <set>
#include <string>
#include <complex>
#include <bitset>
using namespace std;
typedef long long LL;
typedef long double LB;
typedef complex<double> C;
const double pi = acos(-1);
const int MAXN = 100011;
int n,m,a[MAXN];
map<int,int>mp;
map<int,int>tmp;
map<int,LL>ans;
inline LL gcd(LL x,LL y){ if(y==0) return x; return gcd(y,x%y); }
inline int getint(){
    int w=0,q=0; char c=getchar(); while((c<'0'||c>'9') && c!='-') c=getchar();
    if(c=='-') q=1,c=getchar(); while (c>='0'&&c<='9') w=w*10+c-'0',c=getchar(); return q?-w:w;
}

inline void work(){
	n=getint(); for(int i=1;i<=n;i++) a[i]=getint();
	map<int,int>::iterator it;
	for(int i=1;i<=n;i++) {
		tmp.clear();
		for(it=mp.begin();it!=mp.end();it++) 
			tmp[gcd(a[i],it->first)]+=it->second;
		tmp[a[i]]++;
		for(it=tmp.begin();it!=tmp.end();it++) 
			ans[it->first]+=it->second;
		mp=tmp;
	}

	m=getint(); int x;
	for(int i=1;i<=m;i++)
		x=getint(),printf("%I64d\n",ans[x]);
}

int main()
{
    work();
    return 0;
}
//有志者,事竟成,破釜沉舟,百二秦关终属楚;苦心人,天不负,卧薪尝胆,三千越甲可吞吴。

  

 

转载于:https://www.cnblogs.com/ljh2000-jump/p/6533367.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值