跳到正文

个人记录

AtCoder-abc339_f

Chthohepta约 4 分钟
原文
文章信息与版本

文章信息

发布
2025年7月26日
收录
2025年12月12日
更新
2026年11月8日
篇幅
约 4 分钟

版本

  1. v1当前

题意

给定序列 aa,找出满足三元组 (x,y,z)(x,y,z) 的数量。

ax+ay=aza_x + a_y = a_z

思路

一眼哈希。

考虑等式左右两边,左边只有 n2n^2 种状态,右侧只有 nn 种,所以可以通过哈希快速对比。

哈希可以将状态分散到更大的值域当中,这样可以在冲突概率较小的情况下求得答案。

我们可以先求得所有 ai×aja_i \times a_j 的哈希值,然后快速比对。

代码

C++
#include <bits/stdc++.h>
#define ll long long
using namespace std;
ll read(){ ll x = 0, f = 1; char ch = getchar(); while(ch < '0' || ch > '9'){ if(ch == '-'){ f = -1; } ch = getchar(); } while(ch >= '0' && ch <= '9'){ x = x * 10 + ch - '0', ch = getchar(); } return x * f; }
void write(ll x) { if(x < 0){ putchar('-'), x = -x; } if(x > 9){ write(x / 10); } putchar(x % 10 + '0'); }
string reads(){ string s = ""; char ch = getchar(); while(ch != ' ' && ch != '\n'){ s += ch; ch = getchar(); } return s; }
void writes(string s){ for(int i = 0; i < s.size(); i ++){ putchar(s[i]); } }

const int N = 1e3 + 2, mod = 998244353, mod2 = 1e9 + 7, mod3 = 1e9 + 91;
ll n, a[N], b[N], c[N];

struct P{
    ll a, b, c;

    bool operator < (const P &x) const{
        if(a == x.a){
            if(b == x.b) return c < x.c;
            return b < x.b;
        }
        return a < x.a;
    }
}qt;
map <P, int> mp;

string s;
int ans;

int main(){

    n = read();
    for(int i = 1; i <= n; i ++){
        s = reads();
        for(int j = 0; j < s.size(); j ++){
            a[i] = (a[i] * 10 + s[j] - '0') % mod;
            b[i] = (b[i] * 10 + s[j] - '0') % mod2;
            c[i] = (c[i] * 10 + s[j] - '0') % mod3;
        }
    }

    for(int i = 1; i <= n; i ++){
        for(int j = 1; j <= n; j ++){
            qt = {(a[i] * a[j]) % mod, (b[i] * b[j]) % mod2, (c[i] * c[j]) % mod3};
            mp[qt] ++;
        }
    }

    for(int i = 1; i <= n; i ++){
        ans += mp[{a[i], b[i], c[i]}];
    }
    write(ans);

    return 0;
}
原文