SlideShare a Scribd company logo
Data Structure - Tree
Binary Index Tree
Problem:
Give an array A[1], A[2] , … , A[n] and m
queries as follows (n, m ~ 10^6)
type 1: add x to A[k] (1 <= k <= n)
type 2: calculate sum of interval [l , r] of array
Binary Index Tree
Naive solution
type 1: O(1)
type 2: O(n)
→ time complexity O(mn)
m, n ~ 10^6 → impossible
Binary Index Tree
• Fenwick Tree (also called BIT)
• Peter M. Fenwick, "A New Data Structure for
Cumulative Frequency Tables" (1994)
• Support fast operations on array
Binary Index Tree
Support two operations in O(log(n))
[1] Add value x to an element A[k]
A[k] → A[k] + x
[2] Return sum of prefix k
prefix[k] = A[1] + A[2] + ... + A[k]
Binary Index Tree
A[1] + A[2] + A[3] + A[4] A[5] + A[6] + A[7] + A[8]
A[1] + A[2] + A[3] + A[4] + A[5] + A[6] + A[7] + A[8]
A[1] + A[2] A[3] + A[4] A[5] + A[6] A[7] + A[8]
A[1] A[2] A[3] A[4] A[5] A[6] A[7] A[8]
Binary Index Tree
A[1] + A[2] + A[3] + A[4] A[5] + A[6] + A[7] + A[8]
A[1] + A[2] + A[3] + A[4] + A[5] + A[6] + A[7] + A[8]
A[1] + A[2] A[3] + A[4] A[5] + A[6] A[7] + A[8]
A[1] A[2] A[3] A[4] A[5] A[6] A[7] A[8]
add to A[1]
Binary Index Tree
A[1] + A[2] + A[3] + A[4] A[5] + A[6] + A[7] + A[8]
A[1] + A[2] + A[3] + A[4] + A[5] + A[6] + A[7] + A[8]
A[1] + A[2] A[3] + A[4] A[5] + A[6] A[7] + A[8]
A[1] A[2] A[3] A[4] A[5] A[6] A[7] A[8]
add to A[3]
Binary Index Tree
A[1] + A[2] + A[3] + A[4] A[5] + A[6] + A[7] + A[8]
A[1] + A[2] + A[3] + A[4] + A[5] + A[6] + A[7] + A[8]
A[1] + A[2] A[3] + A[4] A[5] + A[6] A[7] + A[8]
A[1] A[2] A[3] A[4] A[5] A[6] A[7] A[8]
get prefix[3]
Binary Index Tree
A[1] + A[2] + A[3] + A[4] A[5] + A[6] + A[7] + A[8]
A[1] + A[2] + A[3] + A[4] + A[5] + A[6] + A[7] + A[8]
A[1] + A[2] A[3] + A[4] A[5] + A[6] A[7] + A[8]
A[1] A[2] A[3] A[4] A[5] A[6] A[7] A[8]
get prefix[7]
Binary Index Tree
• Observation
Express k as binary number
1→1 2→10 3→11 4→100
5→101 6→110 7→111 8→1000
Pay attention to number of ‘0’ at the end
add operation : k → k + (last bit 1 of k)
get operation: k → k – (last bit 1 of k)
Binary Index Tree
[1] Add value to element at position index
void add(int index, int value) {
for (int i = index; i <= size; i += i & -i) {
bit[index] += value;
}
} → O(log(n))
Binary Index Tree
[1] Get sum of elements from postion 1 -> index
int get(int index) {
int ans = 0;
for (int i = index; i > 0; i -= i & -i) {
ans += bit[i];
}
return ans;
} → O(log(n))
Binary Index Tree
• Total time complexity for m queries
Naive: O(mn) → BIT: O(mlog(n))
Amazing 🎉 Bravo 👏
Let see some practical uses of BIT
Count Inverse Pair
Give an array A[1], A[2], ..., A[n], n ~ 10^6
Count number of pair (A[i], A[j]) such that
i < j and A[i] > A[j]
Naive solution: scan all pairs (A[i], A[j]) , i < j
→ time complexity O(n^2) → impossible
Another solution
• Using technique of merge sort
Divide and conquer (A[1], ... ,A[n])
→ (A[1], ... ,A[n/2]) ∨ (A[n/2+1], ..., A[n])
solve(A[1], ... ,A[n/2])
solve(A[n/2+1], ..., A[n])
merge(A[1], ... ,A[n/2] ∨A[n/2+1], ..., A[n])
Time complexity O(nlog(n))
Using BIT
Suppose 1 <= A[1], A[2], ..., A[n] <= n and are
integer.
If not, we can make a mapping by sort because
we only consider about magnitude correlation
ex: (1.2, -9.8, 5.0, 3.4) → (2, 1, 4, 3)
Using BIT
int ans = 0;
void solve() {
for (int i = 1; i <= n; ++i) {
ans += i - 1 - get(a[i]);
add(a[i], 1);
}
}
D-Query
Problem:
Given an array n number A[1], A[2], ..., A[n]
and m queries as follows (n ~ 3x10^4, m ~
2x10^5, 1 <= A[i] <= 10^6)
query : (l, r) return number of distinct
elements in subarray A[l], A[l+1], ..., A[r]
→ Cann’t solve with naive solution
D-Query
Solution with BIT
[1] Sort queries based on right value
(l1,r1), (l2,r2), ..., (lm, rm)
→ r1 <= r2 <= ... <= rm
[2] Go through array from left to right, using
index[] to save last position each value
→ index[x] is last position of x in current array
D-Query
Solution with BIT
[3] Current value a[i]
*if index[a[i]] != i then update index[a[i]] = i
*if there is some r[j] = i then calculate
answer and go to next queries
*else go to next postion
[4] Print answers
D-Query
struct queries {
int l, r, id;
};
bool comp(queries x, queries y) {
return x.r < y.r;
}
sort(queries.begin(), queries.end(), comp);
D-Query
for (int j = 0, i = 1; j < num_queries;) {
if (index[a[i]] != i) {
bit.add(index[a[i]], -1);
index[a[i]] = i;
bit.add(i, 1);
}
if (queries[j].r == i) {
ans[queries[j].id] += bit.get(i) – bit.get(queries[j].l – 1);
j++;
}
else i++;
}
D-Query
1 1 2 1 3
3 queries
[1, 5]
[2, 4]
[3, 5]
index[1] = -1
index[2] = -1
index[3] = -1
3 queries
[2, 4]
[1, 5]
[3, 5]
D-Query
1 1 2 1 3
3 queries
[1, 5]
[2, 4]
[3, 5]
3 queries
[2, 4]
[1, 5]
[3, 5]
index[1] = 1
→ bit.add(-1, -1) , bit.add(1, 1)
index[2] = -1
index[3] = -1
D-Query
1 1 2 1 3
3 queries
[1, 5]
[2, 4]
[3, 5]
3 queries
[2, 4]
[1, 5]
[3, 5]
index[1] = 2
→ bit.add(1, -1) , bit.add(2, 1)
index[2] = -1
index[3] = -1
D-Query
1 1 2 1 3
3 queries
[1, 5]
[2, 4]
[3, 5]
3 queries
[2, 4]
[1, 5]
[3, 5]
index[1] = 2
index[2] = 3
→ bit.add(-1, -1) , bit.add(3, 1)
index[3] = -1
D-Query
1 1 2 1 3
3 queries
[1, 5]
[2, 4]
[3, 5]
3 queries
[2, 4]
[1, 5]
[3, 5]
index[1] = 4
→ bit.add(2, -1) , bit.add(4, 1)
→ ans[2] = bit.get(4) – bit.get(1)
index[2] = 3
index[3] = -1
D-Query
1 1 2 1 3
3 queries
[1, 5]
[2, 4]
[3, 5]
3 queries
[2, 4]
[1, 5]
[3, 5]
index[1] = 4
index[2] = 3
index[3] = 5
→ bit.add(-1, -1) , bit.add(5, 1)
→ ans[1] = bit.get(5) – bit.get(0)
D-Query
1 1 2 1 3
3 queries
[1, 5]
[2, 4]
[3, 5]
3 queries
[2, 4]
[1, 5]
[3, 5]
index[1] = 4
index[2] = 3
index[3] = 5
→ ans[3] = bit.get(5) – bit.get(2)
Segment Tree
Problem:
Give an array A[1], A[2], ..., A[n] and m queries
as follows (n, m ~ 10^6)
type 1: add x to A[k]
type 2: calculate max, min on interval [l, r]
Segment Tree
Naive solution
Same as previous one
type 1: O(1)
type 2: O(n)
→ time complexity O(mn)
→ impossible when n, m ~ 10^6
Segment Tree
• Discoverd by Bentley in 1977 in “Solution to
Klee’s rectangle problems”
• Support fast operations on interval
Segment Tree
A[1] + A[2] + A[3] + A[4] A[5] + A[6] + A[7] + A[8]
A[1] + A[2] + A[3] + A[4] + A[5] + A[6] + A[7] + A[8]
A[1] + A[2] A[3] + A[4] A[5] + A[6] A[7] + A[8]
A[1] A[2] A[3] A[4] A[5] A[6] A[7] A[8]
Segment Tree
A[1] + A[2] + A[3] + A[4] A[5] + A[6] + A[7] + A[8]
A[1] + A[2] + A[3] + A[4] + A[5] + A[6] + A[7] + A[8]
A[1] + A[2] A[3] + A[4] A[5] + A[6] A[7] + A[8]
A[1] A[2] A[3] A[4] A[5] A[6] A[7] A[8]
add to A[2]
Segment Tree
A[1] + A[2] + A[3] + A[4] A[5] + A[6] + A[7] + A[8]
A[1] + A[2] + A[3] + A[4] + A[5] + A[6] + A[7] + A[8]
A[1] + A[2] A[3] + A[4] A[5] + A[6] A[7] + A[8]
A[1] A[2] A[3] A[4] A[5] A[6] A[7] A[8]
add to A[6]
Segment Tree
A[1] + A[2] + A[3] + A[4] A[5] + A[6] + A[7] + A[8]
A[1] + A[2] + A[3] + A[4] + A[5] + A[6] + A[7] + A[8]
A[1] + A[2] A[3] + A[4] A[5] + A[6] A[7] + A[8]
A[1] A[2] A[3] A[4] A[5] A[6] A[7] A[8]
get max on [3,8]
Segment Tree
• Each node of tree is an interval [l, r]
• If l < r, it has two children [l, m] and [m+1, r]
with m = (l + r)/2
• Length of array is n → total node of tree is
1 + 2 + 4 + ... + 2^k = 2^(k+1) – 1
k is smallest number such that 2^k >= n
→ total node <= 4n, memory O(n)
Segment Tree
(1 , 4) (5 , 8)
(1 , 8)
(1 , 2) (3 , 4) (5 , 6) (7 , 8)
(1 , 1) (2 , 2) (3 , 3) (4 , 4) (5 , 5) (6 , 6) (7 , 7) (8 , 8)
1
2 3
4 5 6 7
8 9 10 11 12 13 14 15
Segment Tree
*Initialize: build(1, 1, n)
void build(int node, int l, int r) {
if (l == r) {sg[node] = A[l]; return;}
int m = (l + r)/2;
build(node * 2, l, m);
build(node * 2 + 1, m + 1, r);
sg[node] = max(sg[node * 2], sg[node * 2 + 1]);
} → O(n)
Segment Tree
*Add x to A[k]: update(1, 1, n, k, x)
void update(int node, int l, int r, int k, int x) {
if (l == r) {sg[node] = A[k] + x; return;}
int m = (l + r)/2;
if (m >= k) update(node * 2, l, m, k, x);
else update(node * 2 + 1, m + 1, r, k, x);
sg[node] = max(sg[node * 2], sg[node * 2 + 1]);
} → O(log(n))
Segment Tree
*Get max on interval [l,r]: query(1, 1, n, l, r)
int query(int node, int i, int j, int l, int r) {
if (l<=i && j <= r) {return sg[node];}
int m = (i + j)/2;
if (m >= r) return query(node * 2, i, m, l, r);
else if (m < l) return query(node * 2 + 1, m + 1, j, l, r);
else return max(query(node * 2, i, m, l, r),
query(node * 2 + 1, m + 1, j, l, r));
} → O(log(n))
Treap
• What is treap?
• Combination of tree and heap → treap
• Height of tree is proportional to log(n) with
high probability (n is number of keys in
tree)
• Each node has two attributes: key and
priority number
• Key is binary-tree ordered, priority number
is heap ordered
Treap
• Support search, insertion, deletion, merge
and split
• When insert a key, priority number is
randomed → time complexity of all
operations are expected O(log(n))
Treap
50
100
67
50
25
19
12
33
60
73
20
87
key
pri
Treap
typedef struct node {
int val, pri, cnt, sum;
struct node * child[2];
node(int v, int p) : val(v), pri(p), cnt(1), sum(v) {
child[0] = child[1] = NULL;
}
} * node_t;
Treap
int count(node_t t) {
return t ? t->cnt : 0;
}
int sum(node_t t) {
return t ? t->sum : 0;
}
node_t update(node_t t) {
t->cnt = count(t->child[0]) + count(t->child[1]) + 1;
t->sum = sum(t->child[0]) + sum(t->child[1]) + t->val;
return t;
}
Insertion
• Randomize a priority number
• Insert node to tree as binary search tree
• Rotate tree until priority number is heap-
ordered
• Expected time complexity: O(log(n))
Insertion
50
100
67
50
25
19
12
33
60
73
20
87
55
150
Insertion
50
100
67
50
25
19
12
33
60
73
20
87
55
150
Insertion
50
100
67
50
25
19
12
33
60
73
20
87
55
150
Rotation
node_t rotate(node_t t, int b) {
node_t s = t->child[b];
t->child[1-b] = s->child[b];
s->child[b] = t;
update(t);
update(s);
return s;
}
Rotation
Q
CP
BA
P
A Q
CB
Deletion
• Find node as binary search tree
• Bring node to leaf and delete
• Rotate tree until priority number is heap-
ordered
• Expected time complexity: O(log(n))
Deletion
50
100
67
50
25
19
12
33
60
73
20
87
55
150
Deletion
50
100
67
50
25
19
12
33
60
73
20
87
55
150
Deletion
50
100
67
50
25
19
12
33
60
73
55
150
Deletion
50
100
67
50
25
19
12
33
60
73
55
150
Merge-Split
• Merge two treaps into one
• Split treap into two treaps
• Implement indirectly by insertion and
deletion
• Implement directly
• Expected time complexity: O(log(n))
Merge
A B C D
a b
Merge
A B
C D
a
b
Merge
node_t merge(node_t l, node_t r) {
if (!l || !r) return !l ? r : l;
if (l->pri > r->pri) {
l->child[1] = merge(l->child[1], r);
return update(l);
}
else {
r->child[0] = merge(l, r->child[0]);
return update(r);
}
}
Merge → Insert
T
val
pri
merge(treap T, node x)
Ad

More Related Content

What's hot (20)

DISCRETE LOGARITHM PROBLEM
DISCRETE LOGARITHM PROBLEMDISCRETE LOGARITHM PROBLEM
DISCRETE LOGARITHM PROBLEM
MANISH KUMAR
 
04 quadratic equations
04   quadratic equations04   quadratic equations
04 quadratic equations
profashfaq
 
Aaex2 group2
Aaex2 group2Aaex2 group2
Aaex2 group2
Shiang-Yun Yang
 
redes neuronais
redes neuronaisredes neuronais
redes neuronais
Roland Silvestre
 
Ee693 sept2014midsem
Ee693 sept2014midsemEe693 sept2014midsem
Ee693 sept2014midsem
Gopi Saiteja
 
Skiena algorithm 2007 lecture15 backtracing
Skiena algorithm 2007 lecture15 backtracingSkiena algorithm 2007 lecture15 backtracing
Skiena algorithm 2007 lecture15 backtracing
zukun
 
Definite Integrals 8/ Integration by Parts
Definite Integrals 8/ Integration by PartsDefinite Integrals 8/ Integration by Parts
Definite Integrals 8/ Integration by Parts
Lakshmikanta Satapathy
 
CppConcurrencyInAction - Chapter07
CppConcurrencyInAction - Chapter07CppConcurrencyInAction - Chapter07
CppConcurrencyInAction - Chapter07
DooSeon Choi
 
Lec8
Lec8Lec8
Lec8
Anjneya Varshney
 
Pert 05 aplikasi clustering
Pert 05 aplikasi clusteringPert 05 aplikasi clustering
Pert 05 aplikasi clustering
aiiniR
 
5.3 dynamic programming
5.3 dynamic programming5.3 dynamic programming
5.3 dynamic programming
Krish_ver2
 
On Nets and Meshes
On Nets and MeshesOn Nets and Meshes
On Nets and Meshes
Don Sheehy
 
Presentation OCIP2014
Presentation OCIP2014Presentation OCIP2014
Presentation OCIP2014
Fabian Froehlich
 
Further mathematics notes zimsec cambridge zimbabwe
Further mathematics notes zimsec cambridge zimbabweFurther mathematics notes zimsec cambridge zimbabwe
Further mathematics notes zimsec cambridge zimbabwe
Alpro
 
[1062BPY12001] Data analysis with R / week 2
[1062BPY12001] Data analysis with R / week 2[1062BPY12001] Data analysis with R / week 2
[1062BPY12001] Data analysis with R / week 2
Kevin Chun-Hsien Hsu
 
Thesis Defence for Doctor of Information Science
Thesis Defence for Doctor of Information ScienceThesis Defence for Doctor of Information Science
Thesis Defence for Doctor of Information Science
Yuma Inoue
 
Nbvtalkatbzaonencryptionpuzzles
NbvtalkatbzaonencryptionpuzzlesNbvtalkatbzaonencryptionpuzzles
Nbvtalkatbzaonencryptionpuzzles
Nagasuri Bala Venkateswarlu
 
A Generic Algebraic Model for the Analysis of Cryptographic Key Assignment Sc...
A Generic Algebraic Model for the Analysis of Cryptographic Key Assignment Sc...A Generic Algebraic Model for the Analysis of Cryptographic Key Assignment Sc...
A Generic Algebraic Model for the Analysis of Cryptographic Key Assignment Sc...
dhruvgairola
 
Sub1567
Sub1567Sub1567
Sub1567
International Journal of Science and Research (IJSR)
 
Psimd open64 workshop_2012-new
Psimd open64 workshop_2012-newPsimd open64 workshop_2012-new
Psimd open64 workshop_2012-new
dibyendu_das0708
 
DISCRETE LOGARITHM PROBLEM
DISCRETE LOGARITHM PROBLEMDISCRETE LOGARITHM PROBLEM
DISCRETE LOGARITHM PROBLEM
MANISH KUMAR
 
04 quadratic equations
04   quadratic equations04   quadratic equations
04 quadratic equations
profashfaq
 
Ee693 sept2014midsem
Ee693 sept2014midsemEe693 sept2014midsem
Ee693 sept2014midsem
Gopi Saiteja
 
Skiena algorithm 2007 lecture15 backtracing
Skiena algorithm 2007 lecture15 backtracingSkiena algorithm 2007 lecture15 backtracing
Skiena algorithm 2007 lecture15 backtracing
zukun
 
Definite Integrals 8/ Integration by Parts
Definite Integrals 8/ Integration by PartsDefinite Integrals 8/ Integration by Parts
Definite Integrals 8/ Integration by Parts
Lakshmikanta Satapathy
 
CppConcurrencyInAction - Chapter07
CppConcurrencyInAction - Chapter07CppConcurrencyInAction - Chapter07
CppConcurrencyInAction - Chapter07
DooSeon Choi
 
Pert 05 aplikasi clustering
Pert 05 aplikasi clusteringPert 05 aplikasi clustering
Pert 05 aplikasi clustering
aiiniR
 
5.3 dynamic programming
5.3 dynamic programming5.3 dynamic programming
5.3 dynamic programming
Krish_ver2
 
On Nets and Meshes
On Nets and MeshesOn Nets and Meshes
On Nets and Meshes
Don Sheehy
 
Further mathematics notes zimsec cambridge zimbabwe
Further mathematics notes zimsec cambridge zimbabweFurther mathematics notes zimsec cambridge zimbabwe
Further mathematics notes zimsec cambridge zimbabwe
Alpro
 
[1062BPY12001] Data analysis with R / week 2
[1062BPY12001] Data analysis with R / week 2[1062BPY12001] Data analysis with R / week 2
[1062BPY12001] Data analysis with R / week 2
Kevin Chun-Hsien Hsu
 
Thesis Defence for Doctor of Information Science
Thesis Defence for Doctor of Information ScienceThesis Defence for Doctor of Information Science
Thesis Defence for Doctor of Information Science
Yuma Inoue
 
A Generic Algebraic Model for the Analysis of Cryptographic Key Assignment Sc...
A Generic Algebraic Model for the Analysis of Cryptographic Key Assignment Sc...A Generic Algebraic Model for the Analysis of Cryptographic Key Assignment Sc...
A Generic Algebraic Model for the Analysis of Cryptographic Key Assignment Sc...
dhruvgairola
 
Psimd open64 workshop_2012-new
Psimd open64 workshop_2012-newPsimd open64 workshop_2012-new
Psimd open64 workshop_2012-new
dibyendu_das0708
 

Viewers also liked (20)

Binary tree
Binary treeBinary tree
Binary tree
Rajendran
 
Introduction to Data structure & Algorithms - Sethuonline.com | Sathyabama Un...
Introduction to Data structure & Algorithms - Sethuonline.com | Sathyabama Un...Introduction to Data structure & Algorithms - Sethuonline.com | Sathyabama Un...
Introduction to Data structure & Algorithms - Sethuonline.com | Sathyabama Un...
sethuraman R
 
Binary tree
Binary  treeBinary  tree
Binary tree
Vanitha Chandru
 
Data structures
Data structuresData structures
Data structures
IIUI
 
Hash table
Hash tableHash table
Hash table
Rajendran
 
C++ Pointers
C++ PointersC++ Pointers
C++ Pointers
Chaand Sheikh
 
Problem tree
Problem treeProblem tree
Problem tree
Jenny Catherine
 
Chapter04 -- network protocols
Chapter04  -- network protocolsChapter04  -- network protocols
Chapter04 -- network protocols
Raja Waseem Akhtar
 
Unit 6 pointers
Unit 6   pointersUnit 6   pointers
Unit 6 pointers
George Erfesoglou
 
Stack Applications
Stack ApplicationsStack Applications
Stack Applications
Kulachi Hansraj Model School Ashok Vihar
 
Applications of stack
Applications of stackApplications of stack
Applications of stack
eShikshak
 
Binary Search Tree in Data Structure
Binary Search Tree in Data StructureBinary Search Tree in Data Structure
Binary Search Tree in Data Structure
Dharita Chokshi
 
Tree and binary tree
Tree and binary treeTree and binary tree
Tree and binary tree
Zaid Shabbir
 
Developing a problem tree
Developing a problem treeDeveloping a problem tree
Developing a problem tree
National Centre for Sustainability, Swinburne University of Technology
 
Network topology
Network topologyNetwork topology
Network topology
lekshmik
 
Chapter 2 - Operating System Structures
Chapter 2 - Operating System StructuresChapter 2 - Operating System Structures
Chapter 2 - Operating System Structures
Wayne Jones Jnr
 
Operating System 2
Operating System 2Operating System 2
Operating System 2
tech2click
 
Network topology.ppt
Network topology.pptNetwork topology.ppt
Network topology.ppt
Siddique Ibrahim
 
DATA STRUCTURES
DATA STRUCTURESDATA STRUCTURES
DATA STRUCTURES
bca2010
 
Hype vs. Reality: The AI Explainer
Hype vs. Reality: The AI ExplainerHype vs. Reality: The AI Explainer
Hype vs. Reality: The AI Explainer
Luminary Labs
 
Ad

Similar to Datastructure tree (20)

Advanced data structure
Advanced data structureAdvanced data structure
Advanced data structure
Shakil Ahmed
 
19. algorithms and-complexity
19. algorithms and-complexity19. algorithms and-complexity
19. algorithms and-complexity
showkat27
 
11 1. multi-dimensional array eng
11 1. multi-dimensional array eng11 1. multi-dimensional array eng
11 1. multi-dimensional array eng
웅식 전
 
Thinking Functionally In Ruby
Thinking Functionally In RubyThinking Functionally In Ruby
Thinking Functionally In Ruby
Ross Lawley
 
Programming meeting #8
Programming meeting #8Programming meeting #8
Programming meeting #8
Hideyuki Tabata
 
Clojure for Data Science
Clojure for Data ScienceClojure for Data Science
Clojure for Data Science
Mike Anderson
 
R
RR
R
exsuns
 
pradeepbishtLecture13 div conq
pradeepbishtLecture13 div conqpradeepbishtLecture13 div conq
pradeepbishtLecture13 div conq
Pradeep Bisht
 
Elementary Linear Algebra 5th Edition Larson Solutions Manual
Elementary Linear Algebra 5th Edition Larson Solutions ManualElementary Linear Algebra 5th Edition Larson Solutions Manual
Elementary Linear Algebra 5th Edition Larson Solutions Manual
zuxigytix
 
Basic operations by novi reandy sasmita
Basic operations by novi reandy sasmitaBasic operations by novi reandy sasmita
Basic operations by novi reandy sasmita
beasiswa
 
Demonstration/explanation of Bitonic Sort Algorithm
Demonstration/explanation of Bitonic Sort AlgorithmDemonstration/explanation of Bitonic Sort Algorithm
Demonstration/explanation of Bitonic Sort Algorithm
spektrasmith
 
Python Puzzlers
Python PuzzlersPython Puzzlers
Python Puzzlers
Tendayi Mawushe
 
Data Structure Lecture Array and Recursion.pdf
Data Structure Lecture Array and Recursion.pdfData Structure Lecture Array and Recursion.pdf
Data Structure Lecture Array and Recursion.pdf
okokji4201
 
Big datacourse
Big datacourseBig datacourse
Big datacourse
Massimiliano Ruocco
 
Segment tree
Segment treeSegment tree
Segment tree
Shakil Ahmed
 
Numpy tutorial(final) 20160303
Numpy tutorial(final) 20160303Numpy tutorial(final) 20160303
Numpy tutorial(final) 20160303
Namgee Lee
 
array2d.ppt
array2d.pptarray2d.ppt
array2d.ppt
DeveshDewangan5
 
Algebra and function
Algebra and functionAlgebra and function
Algebra and function
Azlan Ahmad
 
Algorithms - "Chapter 2 getting started"
Algorithms - "Chapter 2 getting started"Algorithms - "Chapter 2 getting started"
Algorithms - "Chapter 2 getting started"
Ra'Fat Al-Msie'deen
 
Haskellで学ぶ関数型言語
Haskellで学ぶ関数型言語Haskellで学ぶ関数型言語
Haskellで学ぶ関数型言語
ikdysfm
 
Advanced data structure
Advanced data structureAdvanced data structure
Advanced data structure
Shakil Ahmed
 
19. algorithms and-complexity
19. algorithms and-complexity19. algorithms and-complexity
19. algorithms and-complexity
showkat27
 
11 1. multi-dimensional array eng
11 1. multi-dimensional array eng11 1. multi-dimensional array eng
11 1. multi-dimensional array eng
웅식 전
 
Thinking Functionally In Ruby
Thinking Functionally In RubyThinking Functionally In Ruby
Thinking Functionally In Ruby
Ross Lawley
 
Clojure for Data Science
Clojure for Data ScienceClojure for Data Science
Clojure for Data Science
Mike Anderson
 
pradeepbishtLecture13 div conq
pradeepbishtLecture13 div conqpradeepbishtLecture13 div conq
pradeepbishtLecture13 div conq
Pradeep Bisht
 
Elementary Linear Algebra 5th Edition Larson Solutions Manual
Elementary Linear Algebra 5th Edition Larson Solutions ManualElementary Linear Algebra 5th Edition Larson Solutions Manual
Elementary Linear Algebra 5th Edition Larson Solutions Manual
zuxigytix
 
Basic operations by novi reandy sasmita
Basic operations by novi reandy sasmitaBasic operations by novi reandy sasmita
Basic operations by novi reandy sasmita
beasiswa
 
Demonstration/explanation of Bitonic Sort Algorithm
Demonstration/explanation of Bitonic Sort AlgorithmDemonstration/explanation of Bitonic Sort Algorithm
Demonstration/explanation of Bitonic Sort Algorithm
spektrasmith
 
Data Structure Lecture Array and Recursion.pdf
Data Structure Lecture Array and Recursion.pdfData Structure Lecture Array and Recursion.pdf
Data Structure Lecture Array and Recursion.pdf
okokji4201
 
Numpy tutorial(final) 20160303
Numpy tutorial(final) 20160303Numpy tutorial(final) 20160303
Numpy tutorial(final) 20160303
Namgee Lee
 
Algebra and function
Algebra and functionAlgebra and function
Algebra and function
Azlan Ahmad
 
Algorithms - "Chapter 2 getting started"
Algorithms - "Chapter 2 getting started"Algorithms - "Chapter 2 getting started"
Algorithms - "Chapter 2 getting started"
Ra'Fat Al-Msie'deen
 
Haskellで学ぶ関数型言語
Haskellで学ぶ関数型言語Haskellで学ぶ関数型言語
Haskellで学ぶ関数型言語
ikdysfm
 
Ad

Recently uploaded (20)

P-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 finalP-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 final
bs22n2s
 
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptxSCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
Ronisha Das
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-3-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 5-3-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 5-3-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-3-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Celine George
 
To study the nervous system of insect.pptx
To study the nervous system of insect.pptxTo study the nervous system of insect.pptx
To study the nervous system of insect.pptx
Arshad Shaikh
 
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdfExploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Sandeep Swamy
 
How to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odooHow to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odoo
Celine George
 
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACYUNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
DR.PRISCILLA MARY J
 
Metamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative JourneyMetamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative Journey
Arshad Shaikh
 
Social Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy StudentsSocial Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy Students
DrNidhiAgarwal
 
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Library Association of Ireland
 
The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...
Sandeep Swamy
 
Presentation of the MIPLM subject matter expert Erdem Kaya
Presentation of the MIPLM subject matter expert Erdem KayaPresentation of the MIPLM subject matter expert Erdem Kaya
Presentation of the MIPLM subject matter expert Erdem Kaya
MIPLM
 
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulsepulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
sushreesangita003
 
Unit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdfUnit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdf
KanchanPatil34
 
Odoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo SlidesOdoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo Slides
Celine George
 
Quality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdfQuality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdf
Dr. Bindiya Chauhan
 
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam SuccessUltimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Mark Soia
 
LDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini UpdatesLDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini Updates
LDM Mia eStudios
 
How to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POSHow to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POS
Celine George
 
P-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 finalP-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 final
bs22n2s
 
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptxSCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
Ronisha Das
 
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Celine George
 
To study the nervous system of insect.pptx
To study the nervous system of insect.pptxTo study the nervous system of insect.pptx
To study the nervous system of insect.pptx
Arshad Shaikh
 
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdfExploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Sandeep Swamy
 
How to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odooHow to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odoo
Celine George
 
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACYUNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
DR.PRISCILLA MARY J
 
Metamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative JourneyMetamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative Journey
Arshad Shaikh
 
Social Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy StudentsSocial Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy Students
DrNidhiAgarwal
 
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Library Association of Ireland
 
The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...
Sandeep Swamy
 
Presentation of the MIPLM subject matter expert Erdem Kaya
Presentation of the MIPLM subject matter expert Erdem KayaPresentation of the MIPLM subject matter expert Erdem Kaya
Presentation of the MIPLM subject matter expert Erdem Kaya
MIPLM
 
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulsepulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
sushreesangita003
 
Unit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdfUnit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdf
KanchanPatil34
 
Odoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo SlidesOdoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo Slides
Celine George
 
Quality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdfQuality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdf
Dr. Bindiya Chauhan
 
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam SuccessUltimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Mark Soia
 
LDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini UpdatesLDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini Updates
LDM Mia eStudios
 
How to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POSHow to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POS
Celine George
 

Datastructure tree

  • 2. Binary Index Tree Problem: Give an array A[1], A[2] , … , A[n] and m queries as follows (n, m ~ 10^6) type 1: add x to A[k] (1 <= k <= n) type 2: calculate sum of interval [l , r] of array
  • 3. Binary Index Tree Naive solution type 1: O(1) type 2: O(n) → time complexity O(mn) m, n ~ 10^6 → impossible
  • 4. Binary Index Tree • Fenwick Tree (also called BIT) • Peter M. Fenwick, "A New Data Structure for Cumulative Frequency Tables" (1994) • Support fast operations on array
  • 5. Binary Index Tree Support two operations in O(log(n)) [1] Add value x to an element A[k] A[k] → A[k] + x [2] Return sum of prefix k prefix[k] = A[1] + A[2] + ... + A[k]
  • 6. Binary Index Tree A[1] + A[2] + A[3] + A[4] A[5] + A[6] + A[7] + A[8] A[1] + A[2] + A[3] + A[4] + A[5] + A[6] + A[7] + A[8] A[1] + A[2] A[3] + A[4] A[5] + A[6] A[7] + A[8] A[1] A[2] A[3] A[4] A[5] A[6] A[7] A[8]
  • 7. Binary Index Tree A[1] + A[2] + A[3] + A[4] A[5] + A[6] + A[7] + A[8] A[1] + A[2] + A[3] + A[4] + A[5] + A[6] + A[7] + A[8] A[1] + A[2] A[3] + A[4] A[5] + A[6] A[7] + A[8] A[1] A[2] A[3] A[4] A[5] A[6] A[7] A[8] add to A[1]
  • 8. Binary Index Tree A[1] + A[2] + A[3] + A[4] A[5] + A[6] + A[7] + A[8] A[1] + A[2] + A[3] + A[4] + A[5] + A[6] + A[7] + A[8] A[1] + A[2] A[3] + A[4] A[5] + A[6] A[7] + A[8] A[1] A[2] A[3] A[4] A[5] A[6] A[7] A[8] add to A[3]
  • 9. Binary Index Tree A[1] + A[2] + A[3] + A[4] A[5] + A[6] + A[7] + A[8] A[1] + A[2] + A[3] + A[4] + A[5] + A[6] + A[7] + A[8] A[1] + A[2] A[3] + A[4] A[5] + A[6] A[7] + A[8] A[1] A[2] A[3] A[4] A[5] A[6] A[7] A[8] get prefix[3]
  • 10. Binary Index Tree A[1] + A[2] + A[3] + A[4] A[5] + A[6] + A[7] + A[8] A[1] + A[2] + A[3] + A[4] + A[5] + A[6] + A[7] + A[8] A[1] + A[2] A[3] + A[4] A[5] + A[6] A[7] + A[8] A[1] A[2] A[3] A[4] A[5] A[6] A[7] A[8] get prefix[7]
  • 11. Binary Index Tree • Observation Express k as binary number 1→1 2→10 3→11 4→100 5→101 6→110 7→111 8→1000 Pay attention to number of ‘0’ at the end add operation : k → k + (last bit 1 of k) get operation: k → k – (last bit 1 of k)
  • 12. Binary Index Tree [1] Add value to element at position index void add(int index, int value) { for (int i = index; i <= size; i += i & -i) { bit[index] += value; } } → O(log(n))
  • 13. Binary Index Tree [1] Get sum of elements from postion 1 -> index int get(int index) { int ans = 0; for (int i = index; i > 0; i -= i & -i) { ans += bit[i]; } return ans; } → O(log(n))
  • 14. Binary Index Tree • Total time complexity for m queries Naive: O(mn) → BIT: O(mlog(n)) Amazing 🎉 Bravo 👏 Let see some practical uses of BIT
  • 15. Count Inverse Pair Give an array A[1], A[2], ..., A[n], n ~ 10^6 Count number of pair (A[i], A[j]) such that i < j and A[i] > A[j] Naive solution: scan all pairs (A[i], A[j]) , i < j → time complexity O(n^2) → impossible
  • 16. Another solution • Using technique of merge sort Divide and conquer (A[1], ... ,A[n]) → (A[1], ... ,A[n/2]) ∨ (A[n/2+1], ..., A[n]) solve(A[1], ... ,A[n/2]) solve(A[n/2+1], ..., A[n]) merge(A[1], ... ,A[n/2] ∨A[n/2+1], ..., A[n]) Time complexity O(nlog(n))
  • 17. Using BIT Suppose 1 <= A[1], A[2], ..., A[n] <= n and are integer. If not, we can make a mapping by sort because we only consider about magnitude correlation ex: (1.2, -9.8, 5.0, 3.4) → (2, 1, 4, 3)
  • 18. Using BIT int ans = 0; void solve() { for (int i = 1; i <= n; ++i) { ans += i - 1 - get(a[i]); add(a[i], 1); } }
  • 19. D-Query Problem: Given an array n number A[1], A[2], ..., A[n] and m queries as follows (n ~ 3x10^4, m ~ 2x10^5, 1 <= A[i] <= 10^6) query : (l, r) return number of distinct elements in subarray A[l], A[l+1], ..., A[r] → Cann’t solve with naive solution
  • 20. D-Query Solution with BIT [1] Sort queries based on right value (l1,r1), (l2,r2), ..., (lm, rm) → r1 <= r2 <= ... <= rm [2] Go through array from left to right, using index[] to save last position each value → index[x] is last position of x in current array
  • 21. D-Query Solution with BIT [3] Current value a[i] *if index[a[i]] != i then update index[a[i]] = i *if there is some r[j] = i then calculate answer and go to next queries *else go to next postion [4] Print answers
  • 22. D-Query struct queries { int l, r, id; }; bool comp(queries x, queries y) { return x.r < y.r; } sort(queries.begin(), queries.end(), comp);
  • 23. D-Query for (int j = 0, i = 1; j < num_queries;) { if (index[a[i]] != i) { bit.add(index[a[i]], -1); index[a[i]] = i; bit.add(i, 1); } if (queries[j].r == i) { ans[queries[j].id] += bit.get(i) – bit.get(queries[j].l – 1); j++; } else i++; }
  • 24. D-Query 1 1 2 1 3 3 queries [1, 5] [2, 4] [3, 5] index[1] = -1 index[2] = -1 index[3] = -1 3 queries [2, 4] [1, 5] [3, 5]
  • 25. D-Query 1 1 2 1 3 3 queries [1, 5] [2, 4] [3, 5] 3 queries [2, 4] [1, 5] [3, 5] index[1] = 1 → bit.add(-1, -1) , bit.add(1, 1) index[2] = -1 index[3] = -1
  • 26. D-Query 1 1 2 1 3 3 queries [1, 5] [2, 4] [3, 5] 3 queries [2, 4] [1, 5] [3, 5] index[1] = 2 → bit.add(1, -1) , bit.add(2, 1) index[2] = -1 index[3] = -1
  • 27. D-Query 1 1 2 1 3 3 queries [1, 5] [2, 4] [3, 5] 3 queries [2, 4] [1, 5] [3, 5] index[1] = 2 index[2] = 3 → bit.add(-1, -1) , bit.add(3, 1) index[3] = -1
  • 28. D-Query 1 1 2 1 3 3 queries [1, 5] [2, 4] [3, 5] 3 queries [2, 4] [1, 5] [3, 5] index[1] = 4 → bit.add(2, -1) , bit.add(4, 1) → ans[2] = bit.get(4) – bit.get(1) index[2] = 3 index[3] = -1
  • 29. D-Query 1 1 2 1 3 3 queries [1, 5] [2, 4] [3, 5] 3 queries [2, 4] [1, 5] [3, 5] index[1] = 4 index[2] = 3 index[3] = 5 → bit.add(-1, -1) , bit.add(5, 1) → ans[1] = bit.get(5) – bit.get(0)
  • 30. D-Query 1 1 2 1 3 3 queries [1, 5] [2, 4] [3, 5] 3 queries [2, 4] [1, 5] [3, 5] index[1] = 4 index[2] = 3 index[3] = 5 → ans[3] = bit.get(5) – bit.get(2)
  • 31. Segment Tree Problem: Give an array A[1], A[2], ..., A[n] and m queries as follows (n, m ~ 10^6) type 1: add x to A[k] type 2: calculate max, min on interval [l, r]
  • 32. Segment Tree Naive solution Same as previous one type 1: O(1) type 2: O(n) → time complexity O(mn) → impossible when n, m ~ 10^6
  • 33. Segment Tree • Discoverd by Bentley in 1977 in “Solution to Klee’s rectangle problems” • Support fast operations on interval
  • 34. Segment Tree A[1] + A[2] + A[3] + A[4] A[5] + A[6] + A[7] + A[8] A[1] + A[2] + A[3] + A[4] + A[5] + A[6] + A[7] + A[8] A[1] + A[2] A[3] + A[4] A[5] + A[6] A[7] + A[8] A[1] A[2] A[3] A[4] A[5] A[6] A[7] A[8]
  • 35. Segment Tree A[1] + A[2] + A[3] + A[4] A[5] + A[6] + A[7] + A[8] A[1] + A[2] + A[3] + A[4] + A[5] + A[6] + A[7] + A[8] A[1] + A[2] A[3] + A[4] A[5] + A[6] A[7] + A[8] A[1] A[2] A[3] A[4] A[5] A[6] A[7] A[8] add to A[2]
  • 36. Segment Tree A[1] + A[2] + A[3] + A[4] A[5] + A[6] + A[7] + A[8] A[1] + A[2] + A[3] + A[4] + A[5] + A[6] + A[7] + A[8] A[1] + A[2] A[3] + A[4] A[5] + A[6] A[7] + A[8] A[1] A[2] A[3] A[4] A[5] A[6] A[7] A[8] add to A[6]
  • 37. Segment Tree A[1] + A[2] + A[3] + A[4] A[5] + A[6] + A[7] + A[8] A[1] + A[2] + A[3] + A[4] + A[5] + A[6] + A[7] + A[8] A[1] + A[2] A[3] + A[4] A[5] + A[6] A[7] + A[8] A[1] A[2] A[3] A[4] A[5] A[6] A[7] A[8] get max on [3,8]
  • 38. Segment Tree • Each node of tree is an interval [l, r] • If l < r, it has two children [l, m] and [m+1, r] with m = (l + r)/2 • Length of array is n → total node of tree is 1 + 2 + 4 + ... + 2^k = 2^(k+1) – 1 k is smallest number such that 2^k >= n → total node <= 4n, memory O(n)
  • 39. Segment Tree (1 , 4) (5 , 8) (1 , 8) (1 , 2) (3 , 4) (5 , 6) (7 , 8) (1 , 1) (2 , 2) (3 , 3) (4 , 4) (5 , 5) (6 , 6) (7 , 7) (8 , 8) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
  • 40. Segment Tree *Initialize: build(1, 1, n) void build(int node, int l, int r) { if (l == r) {sg[node] = A[l]; return;} int m = (l + r)/2; build(node * 2, l, m); build(node * 2 + 1, m + 1, r); sg[node] = max(sg[node * 2], sg[node * 2 + 1]); } → O(n)
  • 41. Segment Tree *Add x to A[k]: update(1, 1, n, k, x) void update(int node, int l, int r, int k, int x) { if (l == r) {sg[node] = A[k] + x; return;} int m = (l + r)/2; if (m >= k) update(node * 2, l, m, k, x); else update(node * 2 + 1, m + 1, r, k, x); sg[node] = max(sg[node * 2], sg[node * 2 + 1]); } → O(log(n))
  • 42. Segment Tree *Get max on interval [l,r]: query(1, 1, n, l, r) int query(int node, int i, int j, int l, int r) { if (l<=i && j <= r) {return sg[node];} int m = (i + j)/2; if (m >= r) return query(node * 2, i, m, l, r); else if (m < l) return query(node * 2 + 1, m + 1, j, l, r); else return max(query(node * 2, i, m, l, r), query(node * 2 + 1, m + 1, j, l, r)); } → O(log(n))
  • 43. Treap • What is treap? • Combination of tree and heap → treap • Height of tree is proportional to log(n) with high probability (n is number of keys in tree) • Each node has two attributes: key and priority number • Key is binary-tree ordered, priority number is heap ordered
  • 44. Treap • Support search, insertion, deletion, merge and split • When insert a key, priority number is randomed → time complexity of all operations are expected O(log(n))
  • 46. Treap typedef struct node { int val, pri, cnt, sum; struct node * child[2]; node(int v, int p) : val(v), pri(p), cnt(1), sum(v) { child[0] = child[1] = NULL; } } * node_t;
  • 47. Treap int count(node_t t) { return t ? t->cnt : 0; } int sum(node_t t) { return t ? t->sum : 0; } node_t update(node_t t) { t->cnt = count(t->child[0]) + count(t->child[1]) + 1; t->sum = sum(t->child[0]) + sum(t->child[1]) + t->val; return t; }
  • 48. Insertion • Randomize a priority number • Insert node to tree as binary search tree • Rotate tree until priority number is heap- ordered • Expected time complexity: O(log(n))
  • 52. Rotation node_t rotate(node_t t, int b) { node_t s = t->child[b]; t->child[1-b] = s->child[b]; s->child[b] = t; update(t); update(s); return s; }
  • 54. Deletion • Find node as binary search tree • Bring node to leaf and delete • Rotate tree until priority number is heap- ordered • Expected time complexity: O(log(n))
  • 59. Merge-Split • Merge two treaps into one • Split treap into two treaps • Implement indirectly by insertion and deletion • Implement directly • Expected time complexity: O(log(n))
  • 60. Merge A B C D a b
  • 62. Merge node_t merge(node_t l, node_t r) { if (!l || !r) return !l ? r : l; if (l->pri > r->pri) { l->child[1] = merge(l->child[1], r); return update(l); } else { r->child[0] = merge(l, r->child[0]); return update(r); } }