B3820 小粉兔的元素反应 题解

· · 个人记录

题意:给定序列 a,询问是否存在 i,j(i \ne j) 使得 a_i\times a_j 为 154 或 147 的倍数。

思路:显然,如果存在两个合法的数,那么它们一定可以反应无限次,所以只需要特判掉 \sum\limits_{i=1}^na_i \ge k 的情况。接下来考虑如何寻找合法数,如果直接枚举 i,j,时间复杂度是 O(n^2) 的,只有 80pts。

考虑一个结论:若 a_i\times a_j\equiv0\pmod{P},则一定有 (a_i \bmod P)\times (a_j \bmod P)\equiv0\pmod{P},这样我们就能将值域缩减到 P 以内,分别令 P 等于 154 和 147,枚举 a_i,a_j 对 P 取模的值判断即可。

code:

#include <bits/stdc++.h>
using namespace std;

signed main() {
    cin.tie(0) -> sync_with_stdio(false);
    auto check = [](int P, const auto a) {
        map<int, int> mp;
        for (auto x : a) mp[x % P]++;
        for (auto i : mp)
        for (auto j : mp) {
            if (i.first == j.first && i.second == 1)
                continue;
            if (i.first * j.first % P == 0)
                return true;
        }
        return false;
    };
    int T; cin >> T;
    while (T--) {
        int n; string k; cin >> n >> k;
        vector<int> a(n, 0);
        for (int i = 0; i < n; i++) cin >> a[i];
        if (k.size() <= 16 && accumulate(a.begin(), a.end(), 0ll) >= atoll(k.c_str())) {
            puts("Yes"); continue;
        }
        puts(check(154, a) || check(147, a) ? "Yes" : "No");
    }
    return 0;
}

拓展:P8928