CF1822G题解(Easy)

· · 题解

题意

求有多少长度为 3 的等比数列。注意这里顺序不分先后,也就是说类似 a_1,a_5,a_4 这样的序列也算。

思路

可以考虑枚举最大的那个数,以及两项的比。(题目中为 b,注意仅当那个数整除 b 的平方时才满足条件)这样枚举下来的复杂度是 O(n\sqrt{a}) 级别的。考虑到 a 的值域为 10^6,可以通过此题。

如何快速判断一个数存在了几次?可以很容易用 map 来维护。当 b \ne 1 时,判断 mp[x/b] 以及 mp[x/b/b]。如果 b=1,说明三个数是相等的,答案加上 mp[x] * (mp[x] - 1) * (mp[x] - 2)。

答案最后可能很大,达到 n^3 级别。记得开 long long。

代码


#include <bits/stdc++.h>
using namespace std;
#define int long long
map <int, int> mp;
signed main() {
    int t;
    cin >> t;
    while (t--) {
        int n;
        scanf("%lld", &n);
        mp.clear();
        for (int i = 1; i <= n; i++) {
            int x;
            scanf("%lld", &x);
            mp[x]++;
        }
        int ans = 0;
        for (auto i : mp) {
            int x = i.first;
            int cnt = i.second;
            if (i.second > 2) {
                ans += cnt * (cnt - 1) * (cnt - 2);
            }
            for (int j = 2; j * j <= x; j++) {
                if (x % (j * j))continue;
                if (mp[x / j] && mp[x / j / j]) {
                    ans += cnt * mp[x / j] * mp[x / j / j];
                }
            }
        }printf("%lld\n", ans);
    }
    return 0;
}

upd:感谢@sz_mane 提出,题解中 map 部分错误,已改