本文共 2264 字,大约阅读时间需要 7 分钟。
问题描述
小葱喜欢除法,所以他给了你N个数a1, a2, ⋯, aN,并且希望你执行M次操作,每次操作可能有以下两种: 给你三个数l, r, v,你需要将al, al+1, ⋯, ar之间所有v的倍数除以v。 给你两个数l, r,你需要回答al + al+1 + ⋯ + ar的值是多少。 输入格式 第一行两个整数N, M,代表数的个数和操作的次数。 接下来一行N个整数,代表N个数一开始的值。输出格式
对于每一次的第二种操作,输出一行代表这次操作所询问的值。 样例输入5 3
1 2 3 4 5 2 1 5 1 1 3 2 2 1 5 1 2 3 4 5 样例输出15
14 1 2 评测用例规模与约定 对于30%的评测用例,1 ≤ N, M ≤ 1000; 对于另外20%的评测用例,第一种操作中一定有l = r; 对于另外20%的评测用例,第一种操作中一定有l = 1 , r = N; 对于100%的评测用例,1 ≤ N, M ≤ 105,0 ≤ a1, a2, ⋯, aN ≤ 106, 1 ≤ v ≤ 106, 1 ≤ l ≤ r ≤ N。 一开始看这个题,就是线段树嘛,我还想最后一个题目怎么这么简单.就写了线段树,提交了一发,超时了.好吧1e6的数据,不超时才怪…才想起来的树状数组,今天才发现她的魅力.时间复杂度O(logn),空间复杂度O(n).怎么会有这么好的东西…比线段树足足提高了一个档次.两个代码都粘一下吧,毕竟线段树写了很久,第一次正儿八经的自己写线段树. 超时线段树:#include#include #include #include #include using namespace std;const int maxx=1e5+10;int ary[maxx];struct node{ int l; int r; int sum;}p[maxx*4];int n,m;void pushup(int cur){ p[cur].sum=p[2*cur].sum+p[2*cur+1].sum;}void build(int l,int r,int cur){ p[cur].l=l; p[cur].r=r; p[cur].sum=0; if(l==r) { p[cur].sum=ary[l]; return ; } int mid=(l+r)/2; build(l,mid,2*cur); build(mid+1,r,2*cur+1); pushup(cur);}int query(int l,int r,int cur){ if(l<=p[cur].l&&r>=p[cur].r) { return p[cur].sum; } int mid=(p[cur].l+p[cur].r)/2; if(mid>=r) return query(l,r,2*cur); else if(mid =R) update(L,R,v,2*cur); else if(mid
树状数组:
树状数组就是跳跃着去找有关联的一些点,而不像线段树那样去二分找点,这样就大大的节省了时间.而且在空间上不需要开结构体,也节省空间.#include#include #include #include #include #define ll long longusing namespace std;const int maxx=1e5+10;ll ary[maxx];ll tree[maxx];int n,m;int lowbit(int i)//树状数组的精华{ return i&-i;}ll getsum(int i){ ll sum=0; while(i>0) { sum+=tree[i]; i-=lowbit(i); } return sum;}void update(int i,int x){ while(i<=n) { tree[i]+=x; i+=lowbit(i); }}int main(){ scanf("%d%d",&n,&m); for(int i=1;i<=n;i++) { scanf("%d",&ary[i]); update(i,ary[i]); } int t,l,r,v; while(m--) { scanf("%d",&t); if(t==1) { scanf("%d%d%d",&l,&r,&v); while(l<=r) { if(ary[l]%v==0) { update(l,-(ary[l]-ary[l]/v)); ary[l]=ary[l]/v; } ++l; } } else if(t==2) { scanf("%d%d",&l,&r); printf("%lld\n",getsum(r)-getsum(l-1)); } }}
努力加油a啊,(o)/~
转载地址:http://fuxvi.baihongyu.com/