fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4.  
  5. using namespace std;
  6.  
  7. const int MOD = 1e9 + 7;
  8.  
  9. void solve() {
  10. int t;
  11. if (!(cin >> t)) return;
  12.  
  13. vector<pair<int, int>> queries(t);
  14. int max_n = 0;
  15.  
  16. for (int i = 0; i < t; i++) {
  17. cin >> queries[i].first >> queries[i].second;
  18. max_n = max(max_n, queries[i].first);
  19. }
  20.  
  21. // DP table: dp[i][j] is the number of permutations of length i+1
  22. // (using 0 to i) with exactly j distinct MEX values.
  23. vector<vector<long long>> dp(max_n + 1, vector<long long>(max_n + 3, 0));
  24.  
  25. if (max_n >= 2) {
  26. dp[1][3] = 2; // Base case: For N=2, the permutations {0,1} and {1,0} both have 3 distinct MEXes.
  27.  
  28. for (int i = 2; i < max_n; i++) {
  29. for (int j = 3; j <= i + 2; j++) {
  30. dp[i][j] = (dp[i-1][j] * (i - 1) % MOD + 2 * dp[i-1][j-1] % MOD) % MOD;
  31. }
  32. }
  33. }
  34.  
  35. for (int i = 0; i < t; i++) {
  36. int n = queries[i].first;
  37. int k = queries[i].second;
  38.  
  39. if (n == 1) {
  40. // For N=1, the only permutation is {0}, which has exactly 1 distinct MEX value (1).
  41. if (k == 1) cout << 1 << "\n";
  42. else cout << 0 << "\n";
  43. } else {
  44. if (k > n + 1) cout << 0 << "\n";
  45. else cout << dp[n-1][k] << "\n";
  46. }
  47. }
  48. }
  49.  
  50. int main() {
  51. ios_base::sync_with_stdio(false);
  52. cin.tie(NULL);
  53. solve();
  54. return 0;
  55. }
Success #stdin #stdout 0s 5316KB
stdin
3
3 3
1 1
2 3
stdout
2
1
2