F - Product Equality
F - Product Equality
Problem Statement
You are given integers .
Find the number of triples of integers that satisfy the following conditions:
Constraints
Input
The input is given from Standard Input in the following format:
Output
Print the answer as an integer.
Sample Input 1
5
2
3
6
12
24
Sample Output 1
6
The following six triples satisfy the conditions in the problem statement:
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 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 .
解题思路
如果 比较小的话,由于 最大只有 ,因此直接暴力枚举 和 ,然后在哈希表中查有多少个数等于 ,答案累加这个数目。如果 变成题目中的约束,哪怕用 FFT 也很明显会超时。
然后很 trick 的地方是对运算取模。显然如果满足 ,那么必然有 。但反过来如果 则不一定有 ,如果模数 比较小,数据量比较大,那么这个冲突会更明显。
所以这里采用双哈希的做法,取两个 int 范围内尽可能大的质数 和 ,然后对 通过秦九韶算法分别求出模 和 的结果 与 ,用二元组 来表示 的哈希值。
ps:一开始我取 和 结果 WA 了 1 个数据 qwq,所以模数尽量不要取一些特殊值,防止被特殊数据卡。当然用多重哈希的话会更保险。
AC 代码如下,时间复杂度为 :
#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
本文来自博客园,作者:onlyblues,转载请注明原文链接:https://www.cnblogs.com/onlyblues/p/18007036
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探
· 为什么 退出登录 或 修改密码 无法使 token 失效
2023-02-04 G2. Teleporters (Hard Version)
2023-02-04 E. Negatives and Positives