CodeForces 385C Bear and Prime Numbers 素数打表

ゞ 浴缸里的玫瑰 2021-12-10 16:45 336阅读 0赞

第一眼看这道题目的时候觉得可能会很难也看不太懂,但是看了给出的Hint之后思路就十分清晰了

  1. Consider the first sample. Overall, the first sample has 3 queries.
  2. The first query l = 2, r = 11 comes. You need to count f(2) + f(3) + f(5) + f(7) + f(11) = 2 + 1 + 4 + 2 + 0 = 9.
  3. The second query comes l = 3, r = 12. You need to count f(3) + f(5) + f(7) + f(11) = 1 + 4 + 2 + 0 = 7.
  4. The third query comes l = 4, r = 4. As this interval has no prime numbers, then the sum equals 0.

xn的范围在(2 ≤ x**i ≤ 107),而 l, r 的范围在 (2 ≤ l**i ≤ r**i ≤ 2·109) ,易得在计算的时候是不会考虑107 以后了

首先写一个素数快速打表,同时也统计一下在 l, r 范围内每个数满足题目条件的总数 (虽然觉得这样的打表方法的确很慢)

然后注意了,因为查询的次数很多,多达5*104次 ,所以在统计的时候可以算出累计和以节省时间

Source Code:

  1. //#pragma comment(linker, "/STACK:16777216") //for c++ Compiler
  2. #include <stdio.h>
  3. #include <iostream>
  4. #include <fstream>
  5. #include <cstring>
  6. #include <cmath>
  7. #include <stack>
  8. #include <string>
  9. #include <map>
  10. #include <set>
  11. #include <list>
  12. #include <queue>
  13. #include <vector>
  14. #include <algorithm>
  15. #define Max(a,b) (((a) > (b)) ? (a) : (b))
  16. #define Min(a,b) (((a) < (b)) ? (a) : (b))
  17. #define Abs(x) (((x) > 0) ? (x) : (-(x)))
  18. #define MOD 1000000007
  19. #define pi acos(-1.0)
  20. using namespace std;
  21. typedef long long ll ;
  22. typedef unsigned long long ull ;
  23. typedef unsigned int uint ;
  24. typedef unsigned char uchar ;
  25. template<class T> inline void checkmin(T &a,T b){
  26. if(a>b) a=b;}
  27. template<class T> inline void checkmax(T &a,T b){
  28. if(a<b) a=b;}
  29. const double eps = 1e-7 ;
  30. const int N = 210 ;
  31. const int M = 1100011*2 ;
  32. const ll P = 10000000097ll ;
  33. const int MAXN = 10900000 ;
  34. int cnt[MAXN],a[MAXN];
  35. bool check[MAXN];
  36. void init_prime(){
  37. for(int i = 2; i < MAXN; ++i){ //素数打表
  38. if(!check[i]){
  39. for(int j = i; j < MAXN; j += i){
  40. check[j] = true;
  41. cnt[i] += a[j];
  42. }
  43. }
  44. }
  45. }
  46. int main(){
  47. std::ios::sync_with_stdio(false);
  48. int i, j, t, k, u, v, numCase = 0;
  49. int n, q, x, y;
  50. cin >> n;
  51. for(i = 1; i <= n; ++i){
  52. cin >> x;
  53. ++a[x];
  54. }
  55. init_prime();
  56. for(i = 2; i < MAXN; ++i){
  57. cnt[i] += cnt[i - 1]; //作累计和以节省查询时间
  58. }
  59. cin >> t;
  60. while(t--){
  61. cin >> x >> y;
  62. checkmin(x, 10000000);
  63. checkmin(y, 10000000);
  64. cout << cnt[y] - cnt[x - 1] << endl;
  65. }
  66. return 0;
  67. }

转载于:https://www.cnblogs.com/wushuaiyi/p/4314071.html

发表评论

表情:
评论列表 (有 0 条评论,336人围观)

还没有评论,来说两句吧...

相关阅读

    相关 素数

    我们经常会使用到素数打表这个工具,判断方法是多种多样的,下面我列举一种好理解的判断方法 思路: 1、初始化visit数组,初始化为true,用visit\[i\]=tr