AcWing 558. 乘积三元组

题目链接
题目

#include <bits/stdc++.h>
#define pb push_back
#define fi first
#define se second
#define all(x) (x).begin(), (x).end()
#define SZ(x) (int) (x).size()
using namespace std;
typedef pair<int, int> pii;
typedef long long ll;
typedef vector<int> VI;
typedef double db;

const int N = 7010, M = 2e5+10;
int n, a[N], s[M]; // s数组模拟哈希表
void solve() {
  memset(s, 0, sizeof(s));
  cin >> n;
  for (int i = 1; i <= n; i++) cin >> a[i];
  sort(a+1, a+1+n);
  ll res = 0;
  int notZero = 0;
  for (int i = n; i >= 1 && a[i]; i--) {
    notZero++;
    for (int j = 0; j < i; j++) {
      if ((ll) a[i]*a[j] < M) { 
        res += s[a[i]*a[j]]; 
      }
    }
    s[a[i]]++;  // 这一步和两数之和有点像
  }
  int theZero = n - notZero;
  // 从所有零中选3个零 C(3,theZero) 0*0 = 0
  res += (ll) (theZero) * (theZero-1) * (theZero-2) / 6; 
  // 从零中选两个,非零数字选一个 C(2, theZero) * C(1, notZero) 0*num = 0;
  res += (ll) (notZero) * (theZero) * (theZero-1) / 2;
  cout << res << '\n';
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  int tt;
  cin >> tt;
  for (int i = 1; i <= tt; i++) {
    cout << "Case #" << i << ": ";
    solve();
  }
  return 0;
}

posted on 2022-10-04 20:17  chelly酱  阅读(22)  评论(0)    收藏  举报

导航