1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
| #include <bits/stdc++.h>
#define N 62 #define MOD 1000000007 using namespace std;
typedef long long ll;
int numN[N], numM[N]; ll f[N][2][2][2][2]; int k;
ll dfs(int pos, bool valid, bool limitN, bool limitM, bool limitI) {
if (pos < 0) return valid; if (f[pos][valid][limitN][limitM][limitI] >= 0) return f[pos][valid][limitN][limitM][limitI]; ll sum = 0; for (int i = 0; i <= (limitN ? numN[pos] : k - 1); i++) { for (int j = 0; j <= min((limitM ? numM[pos] : k - 1), (limitI ? i : k - 1)); j++) { sum = (sum + dfs(pos - 1, valid | (j > i), limitN & (i == numN[pos]), limitM & (j == numM[pos]),limitI & (i == j))) % MOD; } } f[pos][valid][limitN][limitM][limitI] = sum; return sum; }
ll calc(ll n, ll m) { memset(numN, 0, sizeof numN); memset(numM, 0, sizeof numM); memset(f, -1, sizeof f);
int size1 = 0, size2 = 0; ll tmp1 = n, tmp2 = m; while (tmp1) { numN[size1++] = tmp1 % k; tmp1 /= k; } while (tmp2) { numM[size2++] = tmp2 % k; tmp2 /= k; } return dfs(max(size1, size2) - 1, false, true, true, true); }
int main() { ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr);
memset(f, -1, sizeof f);
int t; cin >> t >> k; while (t--) { ll n, m; cin >> n >> m; cout << calc(n, m) << endl; } return 0; }
|