1. 程式人生 > >UVa 10375 Choose and divide (唯一分解定理)

UVa 10375 Choose and divide (唯一分解定理)

divide include n! reg pan gist inline har class

題目

題目大意

已知\(C(m, n) = m! / (n!(m - n)!)\), 輸入整數\(p\), \(q\), \(r\), \(s\)(\(p ≥ q\), \(r ≥ s\), \(p\), \(q\), \(r\), \(s ≤ 10000\)), 計算\(C(p, q) / C(r, s)\)。輸出保證不超過\(10^8\), 保留\(5\)位小數

題解

這道題還是挺水吧...

首先如果直接算出\(C(p, q)\)\(C(r, s)\)是肯定不可能的, C++存不下這麽大的數。

這時候就要用到唯一分解定理, 根據組合數的定義, 顯然分子分母可以約分, 那麽就可以先預處理出小於10000的每個質數, 並求出\(p!\)

, \(q!\), \((p - q)!\), \(r\), \(s\), \((r - s)!\)的每個質因子的冪,進而表示出\(C(p, q) / C(r, s)\), 最後用cmath庫中的pow函數計算就可以了。

當然這道題也可以暴力邊乘邊除來防止答案太大, 雖然精度損失有點大但也可以過這道題了

代碼

唯一分解定理:

#include <cmath>
#include <cstdio>
#include <vector>
#include <cstring>
std::vector<int> prime;
int power[10000];
int p, q, r, s;
double ans;
bool is_prime[10000];
inline void AddInteger(register int, const int&);
inline void AddFactorial(const int&, const int&);
int main(int argc, char const *argv[]) {
  freopen("test.txt", "w", stdout);
  memset(is_prime, 1, sizeof(is_prime));
  is_prime[0] = is_prime[1] = 0;
  for (register int i(2); i <= 10000; ++i) {
    if (is_prime[i]) {
      prime.push_back(i);
      for (register int j(2); i * j <= 10000; ++j) {
        is_prime[i * j] = 0;
      }
    }
  }
  while (~scanf("%d %d %d %d", &p, &q, &r, &s)) {
    memset(power, 0, sizeof(power));
    AddFactorial(p, 1),
    AddFactorial(q, -1),
    AddFactorial(p - q, -1),
    AddFactorial(r, -1),
    AddFactorial(s, 1),
    AddFactorial(r - s, 1);
    ans = 1.0;
    for (auto i : prime) {
      ans *= pow(double(i), double(power[i]));
    }
    printf("%.5lf\n", ans);
  }
  return 0;
}
inline void AddInteger(register int n, const int &d) {
  for (auto i : prime) {
    if (n == 1) break;
    while (!(n % i)) {
      n /= i,
      power[i] += d;
    }
  }
}
inline void AddFactorial(const int &n, const int &d) {
  for (register int i(1); i <= n; ++i) {
    AddInteger(i, d);
  }
}

暴力:

#include <cstdio>
#include <algorithm>
double ans, p, q, r, s;
int main(int argc, char const *argv[]) {
  while (~scanf("%lf %lf %lf %lf", &p, &q, &r, &s)) {
    q = std::min(q, p - q),
    s = std::min(s, r - s);
    ans = 1.0;
    for (register double i(1.0); i <= q || i <= s; ++i) {
      if (i <= q) ans = ans * (p - q + i) / i;
      if (i <= s) ans = ans / (r - s + i) * i;
    }
    printf("%.5lf\n", ans);
  }
  return 0;
}

UVa 10375 Choose and divide (唯一分解定理)