a53

PrimeQuery_Ionescu

a53
May 12th, 2020
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.39 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. typedef unsigned long long i64;
  4. short n, ind, x;
  5. vector<i64> v, numbers;
  6. unordered_map<i64, short> pos;
  7. vector<short> aib, afis;
  8. i64 check[] {3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41};
  9. inline i64 Multiply(i64 a, i64 b, i64 MOD) {
  10. i64 res(0);
  11. while (b) {
  12. if (b & 1)
  13. res = (res + a) % MOD;
  14. a = (a + a) % MOD;
  15. b >>= 1;
  16. }
  17. return res;
  18. }
  19. inline i64 Powlog(i64 a, i64 b, i64 MOD) {
  20. i64 res(1);
  21. while (b) {
  22. if (b & 1)
  23. res = Multiply(res, a, MOD);
  24. a = Multiply(a, a, MOD);
  25. b >>= 1;
  26. }
  27. return res;
  28. }
  29. inline bool Test(i64 num, i64 baza) {
  30. i64 cn(num - 1), exponent(0);
  31. while (cn % 2 == 0)
  32. ++exponent, cn >>= 1;
  33. i64 x = (num - 1) / (1ULL << exponent), pw = Powlog(baza, x, num);
  34. if (pw == 1 || pw == num - 1)
  35. return true;
  36. for (i64 i = 1; i < exponent; ++i) {
  37. pw = Powlog(pw, 2, num);
  38. if (pw == num - 1)
  39. return true;
  40. }
  41. return false;
  42. }
  43. inline bool Prim(i64 x) {
  44. if (x < 2) return false;
  45. if (x == 2) return true;
  46. if (x % 2 == 0) return false;
  47. bool ok(false);
  48. for (int k = 0; k < 12 && !ok; ++k)
  49. if (x == check[k])
  50. ok = true;
  51. if (!ok) {
  52. ok = true;
  53. for (int k = 0; k < 12 && ok; ++k)
  54. ok = Test(x, check[k]);
  55. }
  56. return ok;
  57. }
  58. inline void Update(int pos) {
  59. for (int i = pos; i <= ind; i += i & -i)
  60. ++aib[i];
  61. }
  62. inline int Query(int pos) {
  63. int sum(0);
  64. for (int i = pos; i > 0; i -= i & -i)
  65. sum += aib[i];
  66. return sum;
  67. }
  68. int main() {
  69. ios_base::sync_with_stdio(false);
  70. ifstream fin("primequery.in");
  71. fin >> n;
  72. v = numbers = vector<i64>(n);
  73. for (int i = 0; i < n; ++i) {
  74. fin >> v[i];
  75. numbers[i] = v[i];
  76. }
  77. fin.close();
  78. sort(numbers.begin(), numbers.end());
  79. numbers.erase(unique(numbers.begin(), numbers.end()), numbers.end());
  80. for (const i64& x : numbers)
  81. pos[x] = ++ind;
  82. aib = vector<short>(ind + 1);
  83. for (int i = 0; i < n; ++i) {
  84. x = pos[v[i]];
  85. afis.emplace_back(Query(x - 1));
  86. if (Prim(v[i]))
  87. Update(x);
  88. }
  89. ofstream fout("primequery.out");
  90. for (const short& x : afis)
  91. fout << x << ' ';
  92. fout.close();
  93. return 0;
  94. }
Add Comment
Please, Sign In to add comment