博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
201709-5 除法 ccf(树状数组)
阅读量:4137 次
发布时间:2019-05-25

本文共 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/

你可能感兴趣的文章
Keil MDK 生成BIN 过程
查看>>
RT-Thread 内核实验 1 任务的基本管理
查看>>
STM32 ADC 采样 频率的确定
查看>>
Source Insight技巧收集
查看>>
Linux Kernel 3.0 版本正式发布!
查看>>
成功移植linux2.6.38内核到TQ2440(转)
查看>>
移植Linux2.6.39到杨创utu2440
查看>>
关于ARM的22个常用概念--的确经典
查看>>
kernel panic No init found的一种解决办法
查看>>
I2C从机挂死分析和解决方法
查看>>
USB OTG功能是什么意思?
查看>>
手机中电容屏和电阻屏有什么区别?
查看>>
Linux终端设备驱动 ----UART的驱动
查看>>
uCGUI使用
查看>>
Linux下SPI驱动的移植和应用程序的测试
查看>>
mini210使用tftp功能
查看>>
mini210的uboot编译使用
查看>>
Sizeof与Strlen的区别与联系
查看>>
Linux Kernel and Android 休眠与唤醒(request_suspend_state)
查看>>
mini210的串口驱动的应用程序
查看>>