D. Counting Rhyme Codeforces Round 904 (Div. 2)

Problem - D - Codeforce

题目大意:有一个长度为n的数组a,如果对于一个数个(a[i],a[j])满足不存在a[k]使a[i]%a[k]=0且a[j]%a[k]=0,则称这个数对是合法的,求合法数对的数量。

1<=n<=1e6;1<=a[i]<=n

思路:如果两个数同时对一个数取模都等于 0,那么这两个数的最大公因数就是那个数的倍数,所以如果一个数x在a中出现或者是a中的数的倍数,那么以x为gcd的数对都是非法的,如果不存在x%a[i]=0那么以这样的x为gcd的数对都是合法的。

        那么我们现在要求的就是以每个数为gcd的数对的数量,记dp[i]为以i为gcd的数对的数量,那么我们首先需要知道a中有多少数%i=0,然后还要减去这些数中以i的倍数为gcd的数,我们用cnt数组记录每个数字在a中出现的次数,s=i的倍数的数量即s=cnt[i]+cnt[2i]+...+cnt[ki](ki<=n)那么dp[i]就等于s*(s-1)/2-dp[2i]-dp[3i]-...-dp[ki](ki<=n),所以根据这个转移式,我们需要从n到1遍历,然后每i步进行枚举,时间复杂度就是O(nlogn)。

        最后统计答案,我们用vis数组记录a中出现的数,然后在dp转移的过程中同时把a中出现的数的倍数也记录下来,这样我们只需要累计vis[i]=0时的dp[i]的值即可。

//#include<__msvc_all_public_headers.hpp>
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll MOD = 1e9 + 7;
const int N = 1e6 + 5;
int n;
ll a[N];
int vis[N];
ll cnt[N];
ll dp[N];
void init()
{
	for (int i = 1; i <= n; i++)
	{
		vis[i] = 0;
		cnt[i] = 0;
		dp[i] = 0;
	}
}
void solve()
{
	cin >> n;
	init();
	for (int i = 1; i <= n; i++)
	{
		cin >> a[i];
		vis[a[i]] = 1;//记录%a[i]==0的数
		cnt[a[i]]++;//记录每个数出现的次数
	}
	for (int i = n; i >= 1; i--)
	{
		ll s = 0;
		for (ll j = i; j <= n; j+=i)
		{
			vis[j] |= vis[i];//如果a[i]出现过,a[i]的倍数就记为1
			s += cnt[j];//求%i=0的数的数量
		}
		dp[i] = s * (s - 1) / 2;//以i为因数的数对数量
		for (int j = 2 * i; j <= n; j+=i)
		{
			dp[i] -= dp[j];//减去以i的倍数为gcd的数的数量
		}
	}
	ll ans = 0;
	for (int i = 1; i <= n; i++)
	{
		if (!vis[i])
		{//i%任意a[i]都不等于0,记录答案
			ans += dp[i];
		}
	}
	cout << ans;
	cout << '\n';
}
int main()
{
	ios::sync_with_stdio(false);
	cin.tie(0);
	int t;
	cin >> t;
	//t = 1;
	while (t--)
	{
		solve();
	}
	return 0;
}

        

猜你喜欢

转载自blog.csdn.net/ashbringer233/article/details/133996099