T753427 久! 题解
T753427 久! 题解
题目大意
给定一个长度为
持久值公式:
解题思路(核心:枚举 GCD + 统计个数)
这道题
正确思路:
- 枚举可能的 gcd 值
g (从1 到10^6 ); - 统计原数组中是
g 的倍数的数有多少个,记为tot ; - 这些数可以组成一个gcd 至少为
g 的子序列,持久值至少为tot \times g ; - 遍历所有
g ,取最大的tot \times g 就是答案。
时间复杂度:
完整代码
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
typedef long long ll;
const int MAXA = 1e6 + 5;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int n;
cin >> n;
vector<int> cnt(MAXA, 0);
// 统计每个数字出现次数
for (int i=0; i<n; i++) {
int x;
cin >> x;
cnt[x]++;
}
ll ans = 0;
// 枚举所有可能的 gcd
for (int g=1; g<MAXA; g++) {
ll tot = 0;
// 统计所有 g 的倍数的数量
for (int mul = g; mul < MAXA; mul += g) {
tot += cnt[mul];
}
// 更新最大持久值
ans = max(ans, tot * g);
}
cout << ans << '\n';
return 0;
}