跳到正文

题解

T753427 久! 题解

xxy150310约 2 分钟
原文
文章信息与版本

文章信息

发布
2026年4月19日
收录
2026年4月19日
更新
2026年11月14日
篇幅
约 2 分钟

版本

  1. v1当前

T753427 久! 题解

题目大意

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

持久值公式:

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

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

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

正确思路:

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

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

完整代码

C++
#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;
}
原文