Problem p02769 (C++)

Buggy submission (status: Runtime Error):
/******* DFS TREE **************
 * https://codeforces.com/contest/1276/problem/B
 */

/* ID: vqt
LANG: C++14
PROB: namenum
*/

// #pragma GCC optimize ("O2")
#pragma GCC optimize("O3")
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#include <unistd.h>

using namespace std;
using namespace __gnu_pbds;
// template <typename T>
// using ordered_set = tree<T, null_type, less<T>, rb_tree_tag,
// tree_order_statistics_node_update>;
#define ordered_set                                                            \
  tree<pair<ll, ll>, null_type, less<pair<ll, ll>>, rb_tree_tag,               \
       tree_order_statistics_node_update>

// defines
#define int long long
typedef long long ll;
#define double long double
#define vec vector
#define vi vector<int>
#define vvi vector<vector<int>>
#define p_q priority_queue
#define min_p_q priority_queue<int, vt<int>, greater<int>>
#define ii pair<int, int>
#define vii vector<ii>
#define F first
#define S second
#define MP make_pair
#define PB push_back
#define ALL(x) begin(x), end(x)
#define SZ(x) ((int)(x).size())
#define FOR(i, a, b) for (int i = (a); i < (b); i++)
#define FORE(i, a, b) for (int i = (a); i <= (b); i++)
#define FORD(i, a, b) for (int i = (a); i >= (b); i--)
// #define UNI(x) (x).resize(unique((x).begin(), (x).end()) - (x).end());
#define SORT_UNIQUE(c)                                                         \
  (sort(c.begin(), c.end()),                                                   \
   c.resize(distance(c.begin(), unique(c.begin(), c.end()))))
#define GET_POS(c, x) (lower_bound(c.begin(), c.end(), (x)) - c.begin())
#define MS0(X) memset((X), 0, sizeof((X)))
#define MS1(X) memset((X), -1, sizeof((X)))
#define RESET(X, y) memset(X, y, sizeof(X))
#define chkmin(a, b) a = min(a, b)
#define chkmax(a, b) a = max(a, b)
#define max3(a, b, c) max(a, max(b, c))
#define min3(a, b, c) min(a, min(b, c))

template <class T> inline void out(T t) { cout << t << "\n"; }
template <class T, class... Ts> inline void out(T t, Ts... ts) {
  cout << t << " ";
  out(ts...);
}

// Universal DEBUG: https://codeforces.com/blog/entry/68809
void __print(int x) { cout << x; }
void __print(long x) { cout << x; }
// void __print(long long x) {cout << x;} //invalid if #define int long long
void __print(unsigned x) { cout << x; }
void __print(unsigned long x) { cout << x; }
void __print(unsigned long long x) { cout << x; }
void __print(float x) { cout << x; }
void __print(double x) { cout << x; }
// void __print(long double x) {cout << x;}
void __print(char x) { cout << '\'' << x << '\''; }
void __print(const char *x) { cout << '\"' << x << '\"'; }
void __print(const string &x) { cout << '\"' << x << '\"'; }
void __print(bool x) { cout << (x ? "true" : "false"); }
template <typename T, typename V> void __print(const pair<T, V> &x) {
  cout << '{';
  __print(x.first);
  cout << ',';
  __print(x.second);
  cout << '}';
}
template <typename T> void __print(const T &x) {
  int f = 0;
  cout << '{';
  for (auto &i : x)
    cout << (f++ ? "," : ""), __print(i);
  cout << "}";
}
void _print() { cout << "]\n"; }
template <typename T, typename... V> void _print(T t, V... v) {
  __print(t);
  if (sizeof...(v))
    cout << ", ";
  _print(v...);
}
#ifndef ONLINE_JUDGE
#define debug(x...)                                                            \
  cout << "[" << #x << "] = [";                                                \
  _print(x)
#else
#define debug(x...)
#endif
/* To debug, just type: debug(x, y, z...). It requires C++ 11 or above.
It can work with: Primitive data types: bool, int, long long, float, ...; pair,
string; Collection types: std::vector, std::map, std::set, ...; Expressions
*/

// permanent constants
const long long INF64 = 1e18;
const int INF32 = 1e9;
const int BIG = (int)(1e9 + 239);
const int MOD =
    1000000007; // (int)1e9+7; //998244353; const ll MOD2 = (ll)MOD * (ll)MOD;
const double PI = 2.0 * acos(0.0); // acos(-1.0L);
const double EPS = static_cast<double>(1e-10);
const int day[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
const int dx[4] = {0, 1, 0, -1};
const int dy[4] = {1, 0, -1, 0};

// random
mt19937 rnd(
    239); //(chrono::high_resolution_clock::now().time_since_epoch().count());

typedef vector<vector<int>> matrix; // matrix Z(n, vector<LL>(n));

/*GRAPH:
        vector<vector<int>> dist; // ma tran dist giua cac dinh
    dist.assign(N, vector<int>(N, INF)); // Khoi tao ma tran dist bang INF
    Cach khac:
    vector<int> p;  vector<vector<int>> g; // khai bao
    p = vector<int>(n); // thay cho resize
        g = vector<vector<int>>(n); // // thay cho resize
*/
// Sort w Lambda Function: sort(begin(v), end(v), [] (int a, int b) { return a >
// b; });

// How to use "accumulate":
// https://www.fluentcpp.com/2017/10/17/stdaccumulate-your-knowledge-on-algorithms/
//  array a: tinh XOR sum tu l den r:
#define XORsum(a, l, r)                                                        \
  accumulate(a + l - 1, a + r, 0, [](int a, int b) { return a ^ b; })

void FILEIO() {
  freopen("in.txt", "r", stdin);
  freopen("out.txt", "w", stdout);
}
// void FILEIO() {  freopen("berries.in", "r", stdin);  freopen("berries.out",
// "w", stdout); } Tricks:
#define odd(x) ((x)&1)
#define even(x) !((x)&1)

int mostSignDigit(int n) {
  double k = log10(n);
  return pow(10, k - floor(k));
}
int numOfDigits(int n) { return floor(log10(n)) + 1; }
bool isPowerOfTwo(int x) {
  return x && (!(x & (x - 1)));
} // first x is for the case x=0

bool allPositive(vector<int> &a) {
  return all_of(begin(a), end(a), [](int x) { return x > 0; });
} // are all of the elements positive?
bool anyPositive(vector<int> &a) {
  return any_of(begin(a), end(a), [](int x) { return x > 0; });
} // is there at least one positive element?
bool nonePositive(vector<int> &a) {
  return none_of(begin(a), end(a), [](int x) { return x > 0; });
} // are none of the elements positive?

//******************

//************ MODULAR ARITHMETIC LIB ***************************
template <int MOD> struct Fp {
  long long val;
  constexpr Fp(long long v = 0) noexcept
      : val(v % MOD) { // dinh nghia Fp(v) = (v % MOD)
    if (val < 0)
      val += MOD;
  }
  constexpr int getmod() { return MOD; } // get MOD
  constexpr Fp operator-() const noexcept {
    return val ? MOD - val : 0;
  } // phep toan "-"
  constexpr Fp operator+(const Fp &r) const noexcept {
    return Fp(*this) += r;
  } // phep toan "+="
  constexpr Fp operator-(const Fp &r) const noexcept {
    return Fp(*this) -= r;
  } // phep toan "-="
  constexpr Fp operator*(const Fp &r) const noexcept {
    return Fp(*this) *= r;
  } // phep toan "*="
  constexpr Fp operator/(const Fp &r) const noexcept {
    return Fp(*this) /= r;
  } // phep toan "/="
  constexpr Fp &operator+=(const Fp &r) noexcept {
    val += r.val;
    if (val >= MOD)
      val -= MOD;
    return *this;
  }
  constexpr Fp &operator-=(const Fp &r) noexcept {
    val -= r.val;
    if (val < 0)
      val += MOD;
    return *this;
  }
  constexpr Fp &operator*=(const Fp &r) noexcept {
    val = val * r.val % MOD;
    return *this;
  }
  constexpr Fp &operator/=(
      const Fp &r) noexcept { // dinh nghia phep chia, dung thuat toan inverse
    long long a = r.val, b = MOD, u = 1, v = 0;
    while (b) {
      long long t = a / b;
      a -= t * b;
      swap(a, b);
      u -= t * v;
      swap(u, v);
    }
    val = val * u % MOD;
    if (val < 0)
      val += MOD;
    return *this;
  }
  constexpr bool operator==(const Fp &r) const noexcept {
    return this->val == r.val;
  }
  constexpr bool operator!=(const Fp &r) const noexcept {
    return this->val != r.val;
  }
  friend constexpr ostream &operator<<(ostream &os, const Fp<MOD> &x) noexcept {
    return os << x.val;
  }
  friend constexpr Fp<MOD> modpow(const Fp<MOD> &a, long long n) noexcept {
    if (n == 0)
      return 1;
    auto t = modpow(a, n / 2);
    t = t * t;
    if (n & 1)
      t = t * a;
    return t;
  }
};

template <class T> struct BiCoef { // tinh C(k, n)
  vector<T> fact_, inv_, finv_;
  constexpr BiCoef() {}
  constexpr BiCoef(int n) noexcept : fact_(n, 1), inv_(n, 1), finv_(n, 1) {
    init(n);
  }
  constexpr void init(int n) noexcept {
    fact_.assign(n, 1), inv_.assign(n, 1), finv_.assign(n, 1);
    int MOD = fact_[0].getmod();
    for (int i = 2; i < n; i++) {
      fact_[i] = fact_[i - 1] * i;          // i!
      inv_[i] = -inv_[MOD % i] * (MOD / i); // inverse cua so i
      finv_[i] = finv_[i - 1] * inv_[i];    // factorial inverse
    }
  }
  constexpr T com(int n, int k) const noexcept { // tinh C(k, n)
    if (n < k || n < 0 || k < 0)
      return 0;
    return fact_[n] * finv_[k] * finv_[n - k];
  }
  constexpr T fact(int n) const noexcept {
    if (n < 0)
      return 0;
    return fact_[n];
  }
  constexpr T inv(int n) const noexcept {
    if (n < 0)
      return 0;
    return inv_[n];
  }
  constexpr T finv(int n) const noexcept {
    if (n < 0)
      return 0;
    return finv_[n];
  }
};

/* VI DU:
const int MOD = 1000000007;
using mint = Fp<MOD>; // mint = modular int
BiCoef<mint> bc; // tao class de tinh C(k, n)
bc.init(500050); // precompute tat ca C(k,n) voi n = 500050, k = 1, n
*/

int n, k;

void solve() {
  cin >> n >> k;
  //	if(k > n) {
  //		cout << C(n, 2*n-1) << endl; return; // C(k, n+k-1): xep k bong vao
  //n ro
  //	}

  using mint = Fp<MOD>; // mint = modular int
  BiCoef<mint> bc;      // tao class de tinh C(k, n)
  bc.init(200050);      // precompute tat ca C(k,n) voi n = 200050, k = 1, n

  mint ans = 0;
  FORE(i, 0, min(k, n)) {    // co i phong khong nguoi
    mint way = bc.com(n, i); // so cach chon i phong khong nguoi = C(i, n)
    // int m = n - i = so phong phai co nguoi >=1, tong so nguoi = n => sau khi
    // bo di m
    //  nguoi thi phai xep n-m nguoi nay vao n-i phong => C(n-m, n-m+n-i-1) =
    //  C(i, n-1) C(i, n-1) = ( C(i, n)/n ) * (n-i) suy ra;
    //		int conguoi = ( ( ( CN[i] * (n-i) )%MOD ) * modInverse(n) ) %
    //MOD;
    mint conguoi = bc.com(n - 1, i);
    ans += way * conguoi;
  }
  cout << ans << endl;
}

signed main() {
  ios_base::sync_with_stdio(false);
  cin.tie();
  FILEIO();
  //  auto beginProgram = chrono::steady_clock::now();

  // int t; cin >> t;
  // FOR(i, 0, t)
  {
    //	  cout << "Case #" << i+1 << ": " << solve() << endl;
    solve();
  }

  //  auto endProgram = chrono::steady_clock::now();
  //  cout << chrono::duration_cast<chrono::milliseconds>(endProgram -
  //  beginProgram).count() << " ms" << endl;

  return 0;
}

//*******************END TEST **************************/


Fixed submission:
/******* DFS TREE **************
 * https://codeforces.com/contest/1276/problem/B
 */

/* ID: vqt
LANG: C++14
PROB: namenum
*/

// #pragma GCC optimize ("O2")
#pragma GCC optimize("O3")
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#include <unistd.h>

using namespace std;
using namespace __gnu_pbds;
// template <typename T>
// using ordered_set = tree<T, null_type, less<T>, rb_tree_tag,
// tree_order_statistics_node_update>;
#define ordered_set                                                            \
  tree<pair<ll, ll>, null_type, less<pair<ll, ll>>, rb_tree_tag,               \
       tree_order_statistics_node_update>

// defines
#define int long long
typedef long long ll;
#define double long double
#define vec vector
#define vi vector<int>
#define vvi vector<vector<int>>
#define p_q priority_queue
#define min_p_q priority_queue<int, vt<int>, greater<int>>
#define ii pair<int, int>
#define vii vector<ii>
#define F first
#define S second
#define MP make_pair
#define PB push_back
#define ALL(x) begin(x), end(x)
#define SZ(x) ((int)(x).size())
#define FOR(i, a, b) for (int i = (a); i < (b); i++)
#define FORE(i, a, b) for (int i = (a); i <= (b); i++)
#define FORD(i, a, b) for (int i = (a); i >= (b); i--)
// #define UNI(x) (x).resize(unique((x).begin(), (x).end()) - (x).end());
#define SORT_UNIQUE(c)                                                         \
  (sort(c.begin(), c.end()),                                                   \
   c.resize(distance(c.begin(), unique(c.begin(), c.end()))))
#define GET_POS(c, x) (lower_bound(c.begin(), c.end(), (x)) - c.begin())
#define MS0(X) memset((X), 0, sizeof((X)))
#define MS1(X) memset((X), -1, sizeof((X)))
#define RESET(X, y) memset(X, y, sizeof(X))
#define chkmin(a, b) a = min(a, b)
#define chkmax(a, b) a = max(a, b)
#define max3(a, b, c) max(a, max(b, c))
#define min3(a, b, c) min(a, min(b, c))

template <class T> inline void out(T t) { cout << t << "\n"; }
template <class T, class... Ts> inline void out(T t, Ts... ts) {
  cout << t << " ";
  out(ts...);
}

// Universal DEBUG: https://codeforces.com/blog/entry/68809
void __print(int x) { cout << x; }
void __print(long x) { cout << x; }
// void __print(long long x) {cout << x;} //invalid if #define int long long
void __print(unsigned x) { cout << x; }
void __print(unsigned long x) { cout << x; }
void __print(unsigned long long x) { cout << x; }
void __print(float x) { cout << x; }
void __print(double x) { cout << x; }
// void __print(long double x) {cout << x;}
void __print(char x) { cout << '\'' << x << '\''; }
void __print(const char *x) { cout << '\"' << x << '\"'; }
void __print(const string &x) { cout << '\"' << x << '\"'; }
void __print(bool x) { cout << (x ? "true" : "false"); }
template <typename T, typename V> void __print(const pair<T, V> &x) {
  cout << '{';
  __print(x.first);
  cout << ',';
  __print(x.second);
  cout << '}';
}
template <typename T> void __print(const T &x) {
  int f = 0;
  cout << '{';
  for (auto &i : x)
    cout << (f++ ? "," : ""), __print(i);
  cout << "}";
}
void _print() { cout << "]\n"; }
template <typename T, typename... V> void _print(T t, V... v) {
  __print(t);
  if (sizeof...(v))
    cout << ", ";
  _print(v...);
}
#ifndef ONLINE_JUDGE
#define debug(x...)                                                            \
  cout << "[" << #x << "] = [";                                                \
  _print(x)
#else
#define debug(x...)
#endif
/* To debug, just type: debug(x, y, z...). It requires C++ 11 or above.
It can work with: Primitive data types: bool, int, long long, float, ...; pair,
string; Collection types: std::vector, std::map, std::set, ...; Expressions
*/

// permanent constants
const long long INF64 = 1e18;
const int INF32 = 1e9;
const int BIG = (int)(1e9 + 239);
const int MOD =
    1000000007; // (int)1e9+7; //998244353; const ll MOD2 = (ll)MOD * (ll)MOD;
const double PI = 2.0 * acos(0.0); // acos(-1.0L);
const double EPS = static_cast<double>(1e-10);
const int day[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
const int dx[4] = {0, 1, 0, -1};
const int dy[4] = {1, 0, -1, 0};

// random
mt19937 rnd(
    239); //(chrono::high_resolution_clock::now().time_since_epoch().count());

typedef vector<vector<int>> matrix; // matrix Z(n, vector<LL>(n));

/*GRAPH:
        vector<vector<int>> dist; // ma tran dist giua cac dinh
    dist.assign(N, vector<int>(N, INF)); // Khoi tao ma tran dist bang INF
    Cach khac:
    vector<int> p;  vector<vector<int>> g; // khai bao
    p = vector<int>(n); // thay cho resize
        g = vector<vector<int>>(n); // // thay cho resize
*/
// Sort w Lambda Function: sort(begin(v), end(v), [] (int a, int b) { return a >
// b; });

// How to use "accumulate":
// https://www.fluentcpp.com/2017/10/17/stdaccumulate-your-knowledge-on-algorithms/
//  array a: tinh XOR sum tu l den r:
#define XORsum(a, l, r)                                                        \
  accumulate(a + l - 1, a + r, 0, [](int a, int b) { return a ^ b; })

void FILEIO() {
  freopen("in.txt", "r", stdin);
  freopen("out.txt", "w", stdout);
}
// void FILEIO() {  freopen("berries.in", "r", stdin);  freopen("berries.out",
// "w", stdout); } Tricks:
#define odd(x) ((x)&1)
#define even(x) !((x)&1)

int mostSignDigit(int n) {
  double k = log10(n);
  return pow(10, k - floor(k));
}
int numOfDigits(int n) { return floor(log10(n)) + 1; }
bool isPowerOfTwo(int x) {
  return x && (!(x & (x - 1)));
} // first x is for the case x=0

bool allPositive(vector<int> &a) {
  return all_of(begin(a), end(a), [](int x) { return x > 0; });
} // are all of the elements positive?
bool anyPositive(vector<int> &a) {
  return any_of(begin(a), end(a), [](int x) { return x > 0; });
} // is there at least one positive element?
bool nonePositive(vector<int> &a) {
  return none_of(begin(a), end(a), [](int x) { return x > 0; });
} // are none of the elements positive?

//******************

//************ MODULAR ARITHMETIC LIB ***************************
template <int MOD> struct Fp {
  long long val;
  constexpr Fp(long long v = 0) noexcept
      : val(v % MOD) { // dinh nghia Fp(v) = (v % MOD)
    if (val < 0)
      val += MOD;
  }
  constexpr int getmod() { return MOD; } // get MOD
  constexpr Fp operator-() const noexcept {
    return val ? MOD - val : 0;
  } // phep toan "-"
  constexpr Fp operator+(const Fp &r) const noexcept {
    return Fp(*this) += r;
  } // phep toan "+="
  constexpr Fp operator-(const Fp &r) const noexcept {
    return Fp(*this) -= r;
  } // phep toan "-="
  constexpr Fp operator*(const Fp &r) const noexcept {
    return Fp(*this) *= r;
  } // phep toan "*="
  constexpr Fp operator/(const Fp &r) const noexcept {
    return Fp(*this) /= r;
  } // phep toan "/="
  constexpr Fp &operator+=(const Fp &r) noexcept {
    val += r.val;
    if (val >= MOD)
      val -= MOD;
    return *this;
  }
  constexpr Fp &operator-=(const Fp &r) noexcept {
    val -= r.val;
    if (val < 0)
      val += MOD;
    return *this;
  }
  constexpr Fp &operator*=(const Fp &r) noexcept {
    val = val * r.val % MOD;
    return *this;
  }
  constexpr Fp &operator/=(
      const Fp &r) noexcept { // dinh nghia phep chia, dung thuat toan inverse
    long long a = r.val, b = MOD, u = 1, v = 0;
    while (b) {
      long long t = a / b;
      a -= t * b;
      swap(a, b);
      u -= t * v;
      swap(u, v);
    }
    val = val * u % MOD;
    if (val < 0)
      val += MOD;
    return *this;
  }
  constexpr bool operator==(const Fp &r) const noexcept {
    return this->val == r.val;
  }
  constexpr bool operator!=(const Fp &r) const noexcept {
    return this->val != r.val;
  }
  friend constexpr ostream &operator<<(ostream &os, const Fp<MOD> &x) noexcept {
    return os << x.val;
  }
  friend constexpr Fp<MOD> modpow(const Fp<MOD> &a, long long n) noexcept {
    if (n == 0)
      return 1;
    auto t = modpow(a, n / 2);
    t = t * t;
    if (n & 1)
      t = t * a;
    return t;
  }
};

template <class T> struct BiCoef { // tinh C(k, n)
  vector<T> fact_, inv_, finv_;
  constexpr BiCoef() {}
  constexpr BiCoef(int n) noexcept : fact_(n, 1), inv_(n, 1), finv_(n, 1) {
    init(n);
  }
  constexpr void init(int n) noexcept {
    fact_.assign(n, 1), inv_.assign(n, 1), finv_.assign(n, 1);
    int MOD = fact_[0].getmod();
    for (int i = 2; i < n; i++) {
      fact_[i] = fact_[i - 1] * i;          // i!
      inv_[i] = -inv_[MOD % i] * (MOD / i); // inverse cua so i
      finv_[i] = finv_[i - 1] * inv_[i];    // factorial inverse
    }
  }
  constexpr T com(int n, int k) const noexcept { // tinh C(k, n)
    if (n < k || n < 0 || k < 0)
      return 0;
    return fact_[n] * finv_[k] * finv_[n - k];
  }
  constexpr T fact(int n) const noexcept {
    if (n < 0)
      return 0;
    return fact_[n];
  }
  constexpr T inv(int n) const noexcept {
    if (n < 0)
      return 0;
    return inv_[n];
  }
  constexpr T finv(int n) const noexcept {
    if (n < 0)
      return 0;
    return finv_[n];
  }
};

/* VI DU:
const int MOD = 1000000007;
using mint = Fp<MOD>; // mint = modular int
BiCoef<mint> bc; // tao class de tinh C(k, n)
bc.init(500050); // precompute tat ca C(k,n) voi n = 500050, k = 1, n
*/

int n, k;

void solve() {
  cin >> n >> k;
  //	if(k > n) {
  //		cout << C(n, 2*n-1) << endl; return; // C(k, n+k-1): xep k bong vao
  //n ro
  //	}

  using mint = Fp<MOD>; // mint = modular int
  BiCoef<mint> bc;      // tao class de tinh C(k, n)
  bc.init(200050);      // precompute tat ca C(k,n) voi n = 200050, k = 1, n

  mint ans = 0;
  FORE(i, 0, min(k, n)) {    // co i phong khong nguoi
    mint way = bc.com(n, i); // so cach chon i phong khong nguoi = C(i, n)
    // int m = n - i = so phong phai co nguoi >=1, tong so nguoi = n => sau khi
    // bo di m
    //  nguoi thi phai xep n-m nguoi nay vao n-i phong => C(n-m, n-m+n-i-1) =
    //  C(i, n-1) C(i, n-1) = ( C(i, n)/n ) * (n-i) suy ra;
    //		int conguoi = ( ( ( CN[i] * (n-i) )%MOD ) * modInverse(n) ) %
    //MOD;
    mint conguoi = bc.com(n - 1, i);
    ans += way * conguoi;
  }
  cout << ans << endl;
}

signed main() {
  ios_base::sync_with_stdio(false);
  cin.tie();
  //  FILEIO();
  //  auto beginProgram = chrono::steady_clock::now();

  // int t; cin >> t;
  // FOR(i, 0, t)
  {
    //	  cout << "Case #" << i+1 << ": " << solve() << endl;
    solve();
  }

  //  auto endProgram = chrono::steady_clock::now();
  //  cout << chrono::duration_cast<chrono::milliseconds>(endProgram -
  //  beginProgram).count() << " ms" << endl;

  return 0;
}

//*******************END TEST **************************/