线段树,区间更新+欧拉函数

来源:互联网 发布:魔兽世界官方数据库 编辑:程序博客网 时间:2024/06/06 12:59

区间更新,学会了一种 新的更新姿势。

HDU 5634 

操作1,给定区间,在区间内的 每个单点,按照函数变换

操作2,区间更新,修个整个区间内所有的值

操作3,求和


#include <cstdio>#include <cstring>#include <iostream>#include <algorithm> #include <math.h>#define lson l,m,rt<<1#define rson m+1,r,rt<<1|1#define ll rt<<1#define rr rt<<1|1using namespace std;typedef long long LL;const int maxn=300001;const int maxm=1e7+1;long long ph[maxm];//打表欧拉void Eor(){memset(ph,0,sizeof(ph));ph[1]=1;for(long long i=2;i<maxm;i++){if(!ph[i]){for(long long j=i;j<maxm;j+=i){if(!ph[j]) ph[j]=j;//i为素数 ph[j]=ph[j]/i*(i-1);}}}} struct Tree{int l,r,len;long long sum,lazy;}tree[maxn<<2];void PushUP(int rt){tree[rt].sum= tree[ll].sum +tree[rr].sum;if(tree[ll].lazy == tree[rr].lazy) tree[rt].lazy = tree[ll].lazy;else tree[rt].lazy = 0;}void PushDown(int rt){if(tree[rt].lazy){tree[rr].lazy = tree[ll].lazy =tree[rt].lazy;tree[ll].sum = tree[ll].len* tree[rt].lazy;tree[rr].sum = tree[rr].len* tree[rt].lazy;}}void build(int l,int r,int rt){tree[rt].l=l; tree[rt].r=r;tree[rt].len=r-l+1;if(l==r){scanf("%lld",&tree[rt].sum);tree[rt].lazy=tree[rt].sum;return ;}int m=(l+r)>>1;build(l,m,ll); build(m+1,r,rr);PushUP(rt);}void update1(int L,int R,int rt){if(tree[rt].lazy && L==tree[rt].l && R==tree[rt].r) {tree[rt].sum = ph[tree[rt].lazy] * tree[rt].len;tree[rt].lazy = ph[tree[rt].lazy];return ;}PushDown(rt);int m=(tree[rt].l+tree[rt].r)>>1;if(R <= m) update1(L,R,ll);<span style="white-space:pre"></span>else if(L > m) update1(L,R,rr);<span style="white-space:pre"></span>else { update1(L,m,ll); update1(m+1,R,rr);}PushUP(rt);}void update2(int L,int R,int neww,int rt){if(L==tree[rt].l && R==tree[rt].r) {tree[rt].sum = 1LL*neww*tree[rt].len;tree[rt].lazy = neww;return ;}PushDown(rt);int m=(tree[rt].l+tree[rt].r)>>1;if(R <= m) update2(L,R,neww,ll);<span style="white-space:pre"></span>else if(L > m) update2(L,R,neww,rr);<span style="white-space:pre"></span>else { update2(L,m,neww,ll); update2(m+1,R,neww,rr);}PushUP(rt);}long long query(int L,int R,int rt){if(L==tree[rt].l && R==tree[rt].r)  return tree[rt].sum;PushDown(rt);int m=(tree[rt].l+tree[rt].r)>>1;if(R <= m) return query(L,R,ll);<span style="white-space:pre"></span>else if(L > m) return query(L,R,rr);<span style="white-space:pre"></span>else return query(L,m,ll)+query(m+1,R,rr);} int main(){int T;int n,m;scanf("%d",&T);Eor();while(T--){scanf("%d%d",&n,&m);build(1,n,1);int tp,l,x,r;while(m--){scanf("%d%d%d",&tp,&l,&r);if(tp==1) update1(l,r,1);else if(tp==2){ scanf("%d",&x); update2(l,r,x,1);}else if(tp==3) printf("%lld\n",query(l,r,1));}}return 0;} 


0 0
原创粉丝点击