UVA 1649 Binomial coefficients( 二分 + 二項式的性質 + 列舉)
阿新 • • 發佈:2018-12-13
AcCode:
#include<bits/stdc++.h> #define M(a, b) make_pair(a, b) using namespace std; typedef long long LL; typedef pair<long long , long long> pll; LL m; priority_queue<pll, vector<pll>, greater<pll> > q; LL C(long long n, int k) { int i; long long f = 1; for(i = 1; i <= k; i++){ //一旦中間有哪一步超過了m那說明這個解就不存在了 if (f /i > m / (n-i+1)) //這樣是對的 return m+1; /*底下的都錯了: if(f > m) if(f*(n-i+1)/i > m) if (f * (n-i+1) > m * i) return m+1; */ f *= (n-i+1); f /= i; } return f; } void solve() { long long left, right, mid, t; int k; for(k = 1; C(2*k, k) <= m; k++){ /* 為什麼二分最開始的邊界是2*k 和 m 答: C(k, n)函式的定義域是2*k ~ m ,在這一定義域內影象是單調遞減的。 注意自變數是n, 不是k !!! */ left = k*2, right = m; while(left <= right){ mid = (left + right) >> 1; t = C(mid, k); if(t == m){ q.push(M(mid, k)); if(mid == k*2) break; q.push(M(mid, mid-k)); break; } else if(t < m) left = mid + 1; else right = mid - 1; } } } int main() { int T; scanf("%d", &T); while(T--){ scanf("%lld", &m); solve(); int len = q.size(); if(len){ cout << len << endl; for(int i = 0; i < len; i++){ printf("(%lld,%lld)%c", q.top().first, q.top().second, i == len-1 ? '\n' : ' '); q.pop(); } } else cout << "0" << endl; } return 0; }