当从素数转化为非素数时,对树状数组进行 -1
当从非素数转化为素数时,对树状数组进行 +1
经理的烦恼
Source : HCPC 2005 Spring | |||
Time limit : 2 sec | Memory limit : 32 M |
Submitted : 2600, Accepted : 610
Jerry是一家公司销售部门的经理。这家公司有很多连锁店,编号为1,2,3,... Jerry每天必须关注每家连锁店的商品数量及其变化,一项很乏味的工作。在连锁店比较少的时候,Jerry喜欢计算编号在[i,j]区间内的连锁店中商品数量为素数的有多少家,但是现在连锁店的数量急剧增长,计算量很大,Jerry很难得出结果。
输入格式
题目有多组输入。每组输入第一行有三个整数:C 连锁店的数量 N 指令的条数 M 每家连锁店初始的商品数量
接下来有N行,每行有一条指令。指令的格式为:
0 x y 连锁店x的商品数量变化值为y,y > 0商品数量增加, y < 0减少
1 i j 输出编号在[i,j]区间内的连锁店中商品数量为素数的有多少家
1 <= i, x, j < 1000000 连锁店中的商品数量a满足 0 <= a < 10000000,C = N = M = 0标志输入结束
输出格式
对于每组输入,输出它的序号。对于一组输入中的1指令输出要求的整数。每组输出后打印一行空行。
样例输入
100000 4 4 0 1 1 1 4 10 0 11 3 1 1 11 20 3 0 1 1 20 0 3 3 1 1 20 0 0 0样例输出
CASE #1: 0 2 CASE #2: 0 1
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
#define maxn 1000010
using namespace std;
int c[maxn],a[maxn];
int n;
bool isp(int x)
{
if(x<2) return false;
for(int i=2;i<=(int)sqrt(double(x));i++){
if(x%i==0) return false;
}
return true;
}
int lowbit(int x)
{
return x&-x;
}
void update(int x,int v)
{
while(x<=n){
c[x]+=v;
x+=lowbit(x);
}
}
int query(int x)
{
int ans=0;
while(x>0){
ans+=c[x];
x-=lowbit(x);
}
return ans;
}
int main()
{
int N,M,k=1;
while(~scanf("%d%d%d",&n,&N,&M)&&(n||N||M)){
memset(c,0,sizeof c);
memset(a,0,sizeof a);
for(int i=1; i<=n; ++i)
a[i] = M;
printf("CASE #%d:\n",k++);
if(isp(M)){
for(int i=1;i<=n;i++){
update(i,1);
}
}
int x,y,z;
for(int i=1;i<=N;i++){
scanf("%d%d%d",&x,&y,&z);
if(x){
printf("%d\n",query(z)-query(y-1));
}
else{
a[y]+=z;
if(isp(a[y])&&!isp(a[y]-z)) update(y,1);//从非素数转化为素数
if(!isp(a[y])&&isp(a[y]-z)) update(y,-1);//从素数转化为非素数
}
}
cout<<endl;
}
return 0;
}