题目
题目链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=3911
题目来源:2016.1.25群赛
简要题意:单点增加,区间修改,区间求和,求素数个数。
题解
由于是第一个线段树,留念一下= =
首先要预处理出素数表,这个欧拉筛筛一下即可。
单点的更新需要一个数组来维护每个位置的数据来更新。
区间的更新需要进行延迟更新来加快速度。
然后线段树数据就是线段内素数的个数,然后更新就是了。
代码
#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <cstring>
#include <stack>
#include <queue>
#include <string>
#include <vector>
#include <set>
#include <map>
#define pb push_back
#define mp make_pair
#define all(x) (x).begin(),(x).end()
#define sz(x) ((int)(x).size())
#define fi first
#define se second
using namespace std;
typedef long long LL;
typedef vector<int> VI;
typedef pair<int,int> PII;
LL powmod(LL a,LL b, LL MOD) {LL res=1;a%=MOD;for(;b;b>>=1){if(b&1)res=res*a%MOD;a=a*a%MOD;}return res;}
// head
const int N = 1e5+5;
const int PN = 1e7+5;
bool vis[PN];
int p[PN/10];
int tot = 0;
void getPrime(int n) {
vis[1] = true;
for (int i = 2; i <= n; i++) {
if (!vis[i]) p[++tot] = i;
for (int j = 1; j<=tot && i*p[j]<=n; j++) {
vis[i*p[j]] = true;
if (i%p[j]==0) break;
}
}
}
struct SegmentTree {
#define lson (rt<<1), L, MID
#define rson (rt<<1|1), MID+1, R
#define lno (rt<<1)
#define rno (rt<<1|1)
#define MID ((L+R)>>1)
static const int TN = N<<2;
int tree[TN];
int val[TN];
int lazy[TN];
void pushUp(int rt) {
tree[rt] = tree[lno] + tree[rno];
}
void pushDown(int rt, int L, int R) {
if (lazy[rt] > 0) {
lazy[lno] = lazy[rno] = lazy[rt];
val[lno] = val[rno] = lazy[rt];
tree[lno] = (MID-L+1) * !vis[val[rt]];
tree[rno] = (R-MID) * !vis[val[rt]];
lazy[rt] = 0;
}
}
void build(int rt, int L, int R) {
lazy[rt] = val[rt] = tree[rt] = 0;
if (L == R) {
scanf("%d", val+rt);
tree[rt] = !vis[val[rt]];
} else {
build(lson);
build(rson);
pushUp(rt);
}
}
void updatePoint(int rt, int L, int R, int x, int v) {
if (L == R) {
val[rt] += v;
tree[rt] = !vis[val[rt]];
return;
}
pushDown(rt, L, R);
if (x <= MID) {
updatePoint(lson, x, v);
} else {
updatePoint(rson, x, v);
}
pushUp(rt);
}
void updateInterval(int rt, int L, int R, int l, int r, int v) {
if (r < L || l > R || r < l) return;
if (L == l && R == r) {
val[rt] = lazy[rt] = v;
tree[rt] = (R-L+1) * !vis[val[rt]];
return;
}
pushDown(rt, L, R);
updateInterval(lson, l, min(MID, r), v);
updateInterval(rson, max(MID+1, l), r, v);
pushUp(rt);
}
int query(int rt, int L, int R, int l, int r) {
if (r < L || l > R || r < l) return 0;
if (L == l && R == r) return tree[rt];
pushDown(rt, L, R);
return query(lson, l, min(MID, r)) + query(rson, max(MID+1, l), r);
}
};
SegmentTree st;
char s[5];
int main() {
getPrime(1e7);
int t, n, q, l, r, v, x;
scanf("%d", &t);
while (t--) {
scanf("%d%d", &n, &q);
st.build(1, 1, n);
for (int i = 0; i < q; i++) {
scanf("%s", s);
if (s[0] == 'A') {
scanf("%d%d", &v, &x);
st.updatePoint(1, 1, n, x, v);
} else if (s[0] == 'R') {
scanf("%d%d%d", &v, &l, &r);
st.updateInterval(1, 1, n, l, r, v);
} else {
scanf("%d%d", &l, &r);
printf("%d\n", st.query(1, 1, n, l, r));
}
}
}
return 0;
}