经理的烦恼
Source : HCPC 2005 Spring | |||
Time limit : 2 sec | Memory limit : 32 M |
Submitted : 2079, Accepted : 487
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
树状数组很经典的题目,通过判断素数否对单位加一减一。敲代码时细心些就差不多了!!本人不细心WA出翔~~
#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <vector>
#include <set>
#include <queue>
#include <stack>
#include <climits>//形如INT_MAX一类的
#define MAX 1050
#define INF 0x7FFFFFFF
# define eps 1e-5
using namespace std;
int c[1000005];
int shop[1000005];
int C,n,m;
int lowbit(int x)
{
return x & (-x);
}
int Sum(int i)
{
int sum = 0;
while(i > 0)
{
sum += c[i];
i -= lowbit(i);
}
return sum;
}
void change(int i,int y)
{
while(i <= C)
{
c[i] += y;
i += lowbit(i);
}
}
bool isprime(int x)
{
if(x <= 1)
return false;
bool tmp = true;
for(int i =2; i * i<=x; i++)
{
if(x % i == 0)
{
tmp = false;
return tmp;
}
}
return tmp;
}
int main()
{
int i,j,a,b,d;
int cnt = 1;
while(cin >> C >> n >> m)
{
if(C == 0 && n == 0 && m == 0)
break;
printf("CASE #%d:\n",cnt++);
memset(c,0,sizeof(c));
if(isprime(m))
{
for(i=1; i<=C; i++)
{
c[i] = lowbit(i);
}
}
for(i=1; i<=C; i++)
shop[i] = m;
for(i=1; i<=n; i++)
{
cin >> a >> b >> d;
if(a == 0)
{
if(isprime(shop[b]))
{
if(isprime(shop[b] + d) == 0)
{
change(b,-1);
}
}
if(isprime(shop[b]) == 0)
{
if(isprime(shop[b] + d) == 1)
{
change(b,1);
}
}
shop[b] += d;
}
if(a == 1)
{
cout << Sum(d) - Sum(b-1) << endl;
}
}
cout << endl;
}
return 0;
}