洛谷 P7517 [省选联考 2021 B 卷] 数对

题目传送门

解题思路

其实你只要知道:

n \times \sum _{i=1} ^{n/i} = n \log n

这题你就秒了。

我们发现 a_i \leq 5 \times 10^5,于是开一个桶来统计每个数出现的数量。

我们只需要枚举每一个数的倍数,然后统计。

最后,如果一个数出现了多次,再特判一下即可。

代码

#include<bits/stdc++.h>
using namespace std;

int n;
int cnt[500001];
int mx;
long long ans;
long long temp;
int main()
{
	ios::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	cin>>n;
	int x;
	for(int i=1;i<=n;i++)
	{
		cin>>x;
		mx=max(mx,x);
		cnt[x]++;
	}
	
	for(int i=1;i<=mx;i++)
	{
		temp=0;
		for(int j=2;j<=mx/i;j++)
		{
			temp+=cnt[i*j];
		}
		temp+=cnt[i]-1;
		temp*=cnt[i];
		ans+=temp;
	}
	cout<<ans;
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值