思路: 树状数组
分析:
1 题目要求的是给定一个区间求这个区间质数的个数
2 题目给定n条命令和每一个店的初始的值,那么我们初始化的时候就要通过推断给定的初始值是否为质数来初始化
3 由于要求的是质数的个数,那么我们能够这么想,如果如今改变了店铺x的值,那么我们通过推断前后是否是质数的关系来更新树状数组
4 求区间的质数的个数的时候直接求就可以
<span style="font-size:14px;">#include <cmath> #include <cstdio> #include <cstring> #include <iostream> #include <algorithm> using namespace std; const int MAX = 1000010; int n,val; int num[MAX]; int treeNum[MAX]; int lowbit(int x)//* { return x&(-x); } int getSum(int x)//* { int sum = 0; while(x) { sum += treeNum[x]; x -= lowbit(x); } return sum; } void add(int x,int val)//* { while(x<MAX) { treeNum[x] += val; x += lowbit(x); } } bool isPrime(int x) { if (x<=1) { return false; } if (x == 2) { return true; } int tmp = sqrt(x); for (int i = 2; i < tmp; i++) { if(x%i == 0) return false; } return true; } void init() { int x = 0; if (isPrime(val)) { x = 1; } memset(treeNum,0,sizeof(treeNum)); for (int i = 1; i <= n; i++) { num[i] = val; add(i,x); } } void solve(int mark,int x,int y) { if (mark == 1) { int ans = getSum(y); ans -= getSum(x-1); printf("%d ",ans); } else { int tmp = num[x]; num[x] += y; if(isPrime(num[x])) { if(!isPrime(tmp)) add(x,1); } else { if(isPrime(tmp)) add(x,-1); } } } int main() { int cas = 1; int m,mark; int x,y; //n as ShopNum m as OrderNum val as InitShopGoodsNum while(scanf("%d%d%d",&n,&m,&val)&&(n+m+val)) { init(); printf("CASE #%d: ", cas++); while(m--) { scanf("%d%d%d",&mark,&x,&y); solve(mark,x,y); } puts(""); } return 0; } </span>