F - Product Equality

F - Product Equality

Problem Statement

You are given $N$ integers $A_1, A_2, \dots, A_N$.
Find the number of triples of integers $(i, j, k)$ that satisfy the following conditions:

  • $1 \le i, j, k \le N$
  • $A_i \times A_j = A_k$

Constraints

  • $1 \le N \le 1000$
  • $\color{red}{1 \le A_i < 10^{1000}}$

Input

The input is given from Standard Input in the following format:

$N$
$A_1$
$A_2$
$\vdots$
$A_N$

Output

Print the answer as an integer.


Sample Input 1

5
2
3
6
12
24

Sample Output 1

6

The following six triples $(i, j, k)$ satisfy the conditions in the problem statement:

  • $(1, 2, 3)$
  • $(1, 3, 4)$
  • $(1, 4, 5)$
  • $(2, 1, 3)$
  • $(3, 1, 4)$
  • $(4, 1, 5)$

Sample Input 2

11
1
2
3
4
5
6
123456789123456789
123456789123456789
987654321987654321
987654321987654321
121932631356500531347203169112635269

Sample Output 2

40

Note that the values of each integer $A_i$ can be huge.


Sample Input 3

9
4
4
4
2
2
2
1
1
1

Sample Output 3

162

Note that there may be duplicates among the values of $A_i$.

 

解题思路

  如果 $a_i$ 比较小的话,由于 $n$ 最大只有 $1000$,因此直接暴力枚举 $a_i$ 和 $a_j$,然后在哈希表中查有多少个数等于 $a_i \times a_j$,答案累加这个数目。如果 $a_i$ 变成题目中的约束,哪怕用 FFT 也很明显会超时。

  然后很 trick 的地方是对运算取模。显然如果满足 $a_i \times a_j = a_k$,那么必然有 $(a_i \bmod m) \times (a_j \bmod m) = a_k \bmod m$。但反过来如果 $(a_i \bmod m) \times (a_j \bmod m) = a_k \bmod m$ 则不一定有 $a_i \times a_j = a_k$,如果模数 $m$ 比较小,数据量比较大,那么这个冲突会更明显。

  所以这里采用双哈希的做法,取两个 int 范围内尽可能大的质数 $m_1$ 和 $m_2$,然后对 $a_i$ 通过秦九韶算法分别求出模 $m_1$ 和 $m_2$ 的结果 $h_1$ 与 $h_2$,用二元组 $(h_1, h_2)$ 来表示 $a_i$ 的哈希值。

  ps:一开始我取 $m_1 = 10^9+7$ 和 $m_2 = 998244353$ 结果 WA 了 1 个数据 qwq,所以模数尽量不要取一些特殊值,防止被特殊数据卡。当然用多重哈希的话会更保险。

  AC 代码如下,时间复杂度为 $O(n \log{A} + n^2 \log{n})$:

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

typedef long long LL;

const int N = 1010, m1 = 999999937, m2 = 998244353;

char s[N];
int h1[N], h2[N];

LL get(int x, int y) {
    return 1ll * x * m2 + y;
}

int main() {
    int n;
    scanf("%d", &n);
    map<LL, int> mp;
    for (int i = 0; i < n; i++) {
        scanf("%s", s);
        for (int j = 0; s[j]; j++) {
            h1[i] = (h1[i] * 10ll + s[j] - '0') % m1;
            h2[i] = (h2[i] * 10ll + s[j] - '0') % m2;
        }
        mp[get(h1[i], h2[i])]++;
    }
    LL ret = 0;
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            int t1 = 1ll * h1[i] * h1[j] % m1;
            int t2 = 1ll * h2[i] * h2[j] % m2;
            ret += mp[get(t1, t2)];
        }
    }
    printf("%lld", ret);
    
    return 0;
}

 

参考资料

  AtCoder Beginner Contest 339:https://www.cnblogs.com/2huk/p/18005328

  AtCoder Beginner Contest 339 A-G:https://zhuanlan.zhihu.com/p/681350652

posted @ 2024-02-04 21:23  onlyblues  阅读(15)  评论(0编辑  收藏  举报
Web Analytics