HDU 1754线段树
2024-09-06 15:15:53
第一个自己动手写的线段树,1Y还是有点小激动哈(虽然是模版题)
1 #include<cstdio>
2 #include<cstring>
3 #include<algorithm>
4 using namespace std;
5 const int SIZE=200005;
6 const int INF=1000000;
7 int maxv[SIZE<<2];
8 int num[SIZE];
9 void build(int l,int r,int rt)
10 {
11 if(l==r){
12 maxv[rt]=num[l];
13 return ;
14 }
15 int mid=(l+r)>>1;
16 build(l,mid,rt<<1);
17 build(mid+1,r,rt<<1|1);
18 maxv[rt]=max(maxv[rt<<1],maxv[rt<<1|1]);
19 }
20 int findmax(int L,int R,int l,int r,int rt)
21 {
22 if(L<=l&&R>=r) return maxv[rt];
23 int mid=(l+r)>>1;
24 int ret=-INF;
25 if(L<=mid) ret=max(ret,findmax(L,R,l,mid,rt<<1));
26 if(R>mid) ret=max(ret,findmax(L,R,mid+1,r,rt<<1|1));
27 return ret;
28 }
29 void update(int l,int r,int rt,int v,int p)
30 {
31 int mid=(l+r)>>1;
32 if(l==r) maxv[rt]=p;
33 else{
34 if(v<=mid) update(l,mid,rt<<1,v,p);
35 else update(mid+1,r,rt<<1|1,v,p);
36 maxv[rt]=max(maxv[rt<<1],maxv[rt<<1|1]);
37 }
38 }
39 int main()
40 {
41 //freopen("data.in","r",stdin);
42 int m,n;
43 int i,j;
44 while(scanf("%d%d",&n,&m)!=EOF)
45 {
46 for(i=1;i<=n;i++)
47 scanf("%d",&num[i]);
48 build(1,n,1);
49 for(i=1;i<=m;i++)
50 {
51 int a,b;
52 char c;
53 getchar();
54 scanf("%c %d %d",&c,&a,&b);
55 if(c=='Q')
56 printf("%d\n",findmax(a,b,1,n,1));
57 else if(c=='U')
58 update(1,n,1,a,b);
59 }
60 }
61 return 0;
62 }
虽然自己理解线段树也不深刻,只是掌握了一点皮毛而已,但是觉得线段树的理解在于它是一颗完全二叉树因此可以以数组的形式表示出来。再加上只要理解好线段树的区间覆盖的问题我想基本的题还是能写了
最新文章
- php实现设计模式之 组合模式
- html5 绘制图片 drawImage
- Entity Framework 实体框架的形成之旅--基类接口的统一和异步操作的实现(3)
- mac在xampp下使用yii2.0开发环境配置
- mongo复习
- Window环境下配置Redis服务的方法及查看缓存数据的工具介绍
- DOM4J方式解析XML文件
- ubuntu环境配置
- Ajax技术--考试计时并自动提交试卷
- noip宝藏
- spring_AOP_annotation
- SSE图像算法优化系列二十四: 基于形态学的图像后期抗锯齿算法--MLAA优化研究。
- rman copy相关
- Java并发程序设计(九)设计模式与并发之不变模式
- 【spring cloud】spring cloud2.X spring boot2.0.4调用feign配置Hystrix Dashboard 和 集成Turbine 【解决:Hystrix仪表盘Unable to connect to Command Metric Stream】【解决:Hystrix仪表盘Loading...】
- sphinx搜索 笔记
- composer ";Failed to decode zlib stream";
- centos-iso介绍
- <;转>;Boost库之asio io_service以及run、run_one、poll、poll_one区别
- AJPFX告诉你MT4平台有什么优势?