fork download
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. typedef long long LL;
  6. const int N = (int) 1e6 + 4005;
  7. const LL mod = (LL) 1e9 + 7;
  8.  
  9. LL c[N], fact[N], inv[N], dp[2005][2005], ans[4005];
  10.  
  11. // calculates (-1)^n
  12. int sign (int n) {
  13. if (n & 1) return -1;
  14. else return 1;
  15. }
  16.  
  17. // calculates a^b % mod
  18. LL modpow (LL a, LL b, LL mod) {
  19. LL res = 1;
  20. while (b) {
  21. if (b & 1) res = (res * a) % mod;
  22. a = (a * a) % mod;
  23. b >>= 1;
  24. }
  25. return res;
  26. }
  27.  
  28. // calculates nCr.
  29. LL C (LL n, LL r) {
  30. if (r < 0 || r > n) return 0;
  31. LL ans = (fact[n] * inv[n - r]) % mod;
  32. return (ans * inv[r]) % mod;
  33. }
  34.  
  35.  
  36. int main () {
  37. fact[0] = 1;
  38. // calculate factorial and inverse modulo p for each factorial.
  39. for (LL i = 0; i < N; i++) fact[i + 1] = (LL) (fact[i] * (i + 1)) % mod;
  40. for (int i = 0; i < N; i++) inv[i] = modpow (fact[i], mod - 2, mod);
  41.  
  42. // process the input and calculate array c_i as shown in the editorial.
  43. int n;
  44. scanf ("%d", &n);
  45. for (int i = 0; i < n; i++) {
  46. int foo;
  47. scanf ("%d", &foo);
  48. c[foo + 1] ++;
  49. }
  50.  
  51. // Now we come for the dp step.
  52. // dp[i][s] = as given in the editorial, coefficient of x^s in first i steps.
  53. dp[0][0] = 1;
  54. for (int i = 1; i <= 1001; i++) {
  55. for (int s = 0; s <= 2000; s++) {
  56. int k = i;
  57. LL sum = 0;
  58. // try all coefficients of x^(k * l), this is crucial step in complexity reduction.
  59. for (int l = 0; l <= s; l++) {
  60. if (k * l > s) break;
  61. // coefficient of x^(k * l) in (x^(i + 1) - 1) ^ c_i
  62. LL prod = C (c[i], l) * sign (c[i] - l);
  63. sum = (sum + dp[i - 1][s - k * l] * prod) % mod;
  64. if (sum < 0) sum += mod;
  65. }
  66. dp[i][s] = sum;
  67. }
  68. }
  69.  
  70. // Now do the multiplication part as shown in the editorial.
  71. for (int i = 0; i <= 2000; i++) {
  72. for (int j = 0; j <= 2000; j++) {
  73. // coefficients of x^j in (x - 1)^(-n) is (-1)^n C (n + j - 1, j), See the given link for explantion.
  74. ans[i + j] = (ans[i + j] + dp[1001][i] * sign (n) * C (n + j - 1, j)) % mod;
  75. if (ans[i + j] < 0) ans[i + j] += mod;
  76. }
  77. }
  78.  
  79. // finally take the query input as given in the problem.
  80. int Q;
  81. scanf ("%d", &Q);
  82. while (Q--) {
  83. int s;
  84. scanf ("%d", &s);
  85. printf ("%lld\n", ans[s]);
  86. }
  87.  
  88. return 0;
  89. }
Runtime error #stdin #stdout 2.63s 58272KB
stdin
Standard input is empty
stdout
Standard output is empty