我是靠谱客的博主 醉熏水杯,这篇文章主要介绍「杭电oj」1166 - 敌兵布阵(线段树裸题),现在分享给大家,希望可以做个参考。

题目链接

线段树保留了二叉树的结构特点,能够在 O(log(n)) O ( l o g ( n ) ) 的时间内查询一些区间的信息,比如区间和,区间最大最小值,而且还支持数据更改。

AC代码:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#include <bits/stdc++.h> using namespace std; const int N = 2e6+100; struct Node{ int l,r; int x; }node[N<<2]; int fa[N]; void BuildTree(int i,int l,int r){ node[i].l = l; node[i].r = r; node[i].x = 0; if(l == r){ fa[l] = i; return; } int mid = (l+r)>>1; BuildTree(i<<1,l,mid); BuildTree(i<<1|1,mid+1,r); } inline void Updata(int x){ if(x == 1) return; int f = x>>1; node[f].x = node[f<<1].x + node[f<<1|1].x; Updata(f); } int ans; inline void Query(int i,int l,int r){ if(node[i].l == l && node[i].r == r){ ans+=node[i].x; return; } i<<=1; if(l <= node[i].r){ if(r <= node[i].r){ Query(i,l,r); } else{ Query(i,l,node[i].r); } } i++; if(r >= node[i].l){ if(l >= node[i].l){ Query(i,l,r); } else{ Query(i,node[i].l,r); } } } int main(int argc, char const *argv[]) { ios::sync_with_stdio(0); int T,kas = 1; cin>>T; while(T--){ int n,x; cin>>n; BuildTree(1,1,n); for(int i=1;i<=n;++i){ cin>>x; node[fa[i]].x = x; Updata(fa[i]); } string op; int a,b; cout<<"Case "<<kas++<<":n"; while(cin>>op && op !="End"){ cin>>a>>b; if(op == "Add"){ node[fa[a]].x += b; Updata(fa[a]); } else if(op == "Sub"){ node[fa[a]].x -= b; Updata(fa[a]); } else{ ans = 0; Query(1,a,b); cout<<ans<<endl; } } } return 0; }

最后

以上就是醉熏水杯最近收集整理的关于「杭电oj」1166 - 敌兵布阵(线段树裸题)的全部内容,更多相关「杭电oj」1166内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(59)

评论列表共有 0 条评论

立即
投稿
返回
顶部