Skip to content

Commit

Permalink
Update manhattan-distances-of-all-arrangements-of-pieces.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
kamyu104 authored Jan 20, 2025
1 parent b677454 commit 11eb3ca
Showing 1 changed file with 35 additions and 35 deletions.
70 changes: 35 additions & 35 deletions C++/manhattan-distances-of-all-arrangements-of-pieces.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,44 @@

// combinatorics
static const uint32_t MOD = 1e9 + 7;

uint32_t addmod(uint32_t a, uint32_t b) { // avoid overflow
a %= MOD, b %= MOD;
if (MOD - a <= b) {
b -= MOD; // relied on unsigned integer overflow in order to give the expected results
}
return a + b;
}

// reference: https://stackoverflow.com/questions/12168348/ways-to-do-modulo-multiplication-with-primitive-types
uint32_t mulmod(uint32_t a, uint32_t b) { // avoid overflow
a %= MOD, b %= MOD;
uint32_t result = 0;
if (a < b) {
swap(a, b);
}
while (b > 0) {
if (b & 1) {
result = addmod(result, a);
}
a = addmod(a, a);
b >>= 1;
}
return result;
}

vector<int> FACT = {1, 1};
vector<int> INV = {1, 1};
vector<int> INV_FACT = {1, 1};
int nCr(int n, int k) {
while (size(INV) <= n) { // lazy initialization
FACT.emplace_back(mulmod(FACT.back(), size(INV)));
INV.emplace_back(mulmod(INV[MOD % size(INV)], MOD - MOD / size(INV))); // https://cp-algorithms.com/algebra/module-inverse.html
INV_FACT.emplace_back(mulmod(INV_FACT.back(), INV.back()));
}
return mulmod(mulmod(FACT[n], INV_FACT[n - k]), INV_FACT[k]);
}

class Solution {
public:
int distanceSum(int m, int n, int k) {
Expand All @@ -27,39 +62,4 @@ class Solution {
const auto y = mulmod(mulmod(f(m) % MOD, n), n);
return mulmod(x + y, nCr(m * n - 2, k - 2));
}

private:
int nCr(int n, int k) {
while (size(INV) <= n) { // lazy initialization
FACT.emplace_back(mulmod(FACT.back(), size(INV)));
INV.emplace_back(mulmod(INV[MOD % size(INV)], MOD - MOD / size(INV))); // https://cp-algorithms.com/algebra/module-inverse.html
INV_FACT.emplace_back(mulmod(INV_FACT.back(), INV.back()));
}
return mulmod(mulmod(FACT[n], INV_FACT[n - k]), INV_FACT[k]);
}

uint32_t addmod(uint32_t a, uint32_t b) { // avoid overflow
a %= MOD, b %= MOD;
if (MOD - a <= b) {
b -= MOD; // relied on unsigned integer overflow in order to give the expected results
}
return a + b;
}

// reference: https://stackoverflow.com/questions/12168348/ways-to-do-modulo-multiplication-with-primitive-types
uint32_t mulmod(uint32_t a, uint32_t b) { // avoid overflow
a %= MOD, b %= MOD;
uint32_t result = 0;
if (a < b) {
swap(a, b);
}
while (b > 0) {
if (b & 1) {
result = addmod(result, a);
}
a = addmod(a, a);
b >>= 1;
}
return result;
}
};

0 comments on commit 11eb3ca

Please sign in to comment.