题目要求
有一个长度为n的数组a
数组的子序列的最小公倍数不包含在a中,叫这个子序列为特殊子序列
空子序列的LCM等于0
问你a中最长的特殊子序列的长度是多少
思路
我们可以发现只有两种情况,要不就是大于max_ elements,要不就是等于max _elements。
① 如果大于max_elements,那么题目的答案直接输出n即可。
②而对于等于max_elements,我们可以发现数组a中的数都是max _elements的约数,我们最后得到的最大的特殊子序列的lcm也一定是max _elements的约束,那么我们就可以枚举max _elements的所有约数,然后去求能够满足条件的不存在数组a中的所有约数,能得到的最大的特殊子序列的长度。
代码
#define _CRT_SECURE_NO_WARNINGS
#include<bits/stdc++.h>
using namespace std;
#define IOS ios::sync_with_stdio(false),cin.tie(0),cout.tie(0)
#define endl "\n"
#define int long long
#define debug(x) cout << #x << " " << x << endl
const int INF = 1e9 + 7;
int gcd(int a, int b)
{
return b ? gcd(b, a % b) : a;
}
int lcm(int a, int b)
{
return (a * b) / gcd(a, b);
}
void solve()
{
int n;
cin >> n;
vector<int> a(n);
int max_lcm = 1;
for (int i = 0; i < n; i++) {
cin >> a[i];
max_lcm = lcm(max_lcm, a[i]);
max_lcm = min(max_lcm, INF);
}
int max_facts = *max_element(a.begin(), a.end());
if (max_lcm > max_facts) {
cout << n << endl;
return;
}
// 相等的情况
set<int> s(a.begin(), a.end());
vector<int> factor;
for (int i = 1; i * i <= max_lcm; i++)
{
if (max_lcm % i == 0)
{
if (!s.count(i)) factor.push_back(i);
if (i * i != max_lcm && !s.count(max_lcm / i))
{
factor.push_back(max_lcm / i);
}
}
}
// 计算结果
int ans = 0;
for (int i = 0; i < factor.size(); i++)
{
int cnt = 0;
int num = 1; // 存lcm值
int x = factor[i];
for (int j = 0; j < n; j++)
{
if (x % a[j] == 0)
{
cnt++;
num = lcm(num, a[j]);
}
}
if (num == x)
{
ans = max(ans, cnt);
}
}
cout << ans << endl;
}
signed main()
{
IOS;
int T;
cin >> T;
while (T--)
{
solve();
}
return 0;
}