T753427 久! 题解

· · 题解

T753427 久! 题解

题目大意

给定一个长度为 n 的正整数序列,我们需要找出所有非空子序列中,持久值最大的那一个。

持久值公式:

\text{持久值} = \text{子序列长度} \times \gcd(\text{子序列所有元素})

解题思路(核心:枚举 GCD + 统计个数)

这道题 n 最大到 2 \times 10^5,不能暴力枚举所有子序列(会超时)。

正确思路:

  1. 枚举可能的 gcd 值 g(从 1 到 10^6);
  2. 统计原数组中是 g 的倍数的数有多少个,记为 tot;
  3. 这些数可以组成一个gcd 至少为 g 的子序列,持久值至少为 tot \times g;
  4. 遍历所有 g,取最大的 tot \times g 就是答案。

时间复杂度:O(MAXA \log MAXA),完全能通过题目数据。

完整代码

#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;
}