🟫

ABC292-C: Four Variables 解説

2023/03/05に公開

問題

正整数Nが与えられるので,AB + CD = Nを満たす(A,B,C,D)の組の個数を出力してください

制約

2 \leq N \leq 2 \times 10^5
答えは9 \times 10^{18}以下であることが保証される

https://atcoder.jp/contests/abc292/tasks/abc292_c

コンテスト中に考えたこと

  • 計算量的にO(N^2)が通らない
  • AB=Nを満たす(A,B)の組の総数はO(\sqrt(N))で求められるのでこれを使えば良さそう
  • ABCDかのどちらかが決まれば両方決まるので,片方を1以上N以下で探索すると良さそう

解説

  • ABを固定すると,CD = N - ABとなる
  • 積がNとなるペアの総数を求める関数をf(N)とすると,答えは\sum_{i=1}^{N-1}{f(i) \times f(N - i)}
  • 関数f(N)は積がNになるペアのうち,少なくとも一方は\sqrt N以下であることを用いることでO(\sqrt N)で動作する
  • そのため全体としてO(N\sqrt N)で解くことができる
コード
#include<bits/stdc++.h>
using ll = long long;
using namespace std;

ll countProductPairs(ll N){
  ll res = 0;
  for(ll i = 1; i * i <= N; ++i){
    if(N % i == 0){
      if(i * i == N) res += 1;
      else res += 2; // (A,B) = (i, N/i), (N/i, i)
    }
  }
  return res;
}

int main(){
  int N;
  cin >> N;

  ll ans = 0;
  for(ll i = 1; i < N; ++i){
    ans += countProductPairs(i) * countProductPairs(N - i);
  }
  cout << ans << endl;
}

https://atcoder.jp/contests/abc292/submissions/39462617

GitHubで編集を提案

Discussion