F - Product Equality

F - Product Equality

Problem Statement

You are given N integers A1,A2,,AN.
Find the number of triples of integers (i,j,k) that satisfy the following conditions:

  • 1i,j,kN
  • Ai×Aj=Ak

Constraints

  • 1N1000
  • 1Ai<101000

Input

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

N
A1
A2

AN

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 Ai 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 Ai.

 

解题思路

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

  然后很 trick 的地方是对运算取模。显然如果满足 ai×aj=ak,那么必然有 (aimodm)×(ajmodm)=akmodm。但反过来如果 (aimodm)×(ajmodm)=akmodm 则不一定有 ai×aj=ak,如果模数 m 比较小,数据量比较大,那么这个冲突会更明显。

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

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

  AC 代码如下,时间复杂度为 O(nlogA+n2logn)

#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 @   onlyblues  阅读(34)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探
· 为什么 退出登录 或 修改密码 无法使 token 失效
历史上的今天:
2023-02-04 G2. Teleporters (Hard Version)
2023-02-04 E. Negatives and Positives
Web Analytics
点击右上角即可分享
微信分享提示