AVL Tree
Adelson-Velsky andLandis Tree is a self-balancing binary search tree.
► abs(h(left subtree) – h(right subtree)) <= 1
12
8
18
5
11
4
17
https://www.geeksforgeeks.org/introduction-to-avl-tree/
12.
Red-Black Tree
a self-balancingbinary search tree.
► Every node is either red or black.
► Root node is black.
► Red node can’t have red parent or red child.
► Every path from a node to descendant
leaf has same number of black nodes.
► Every leaf must be colored black.
7
3
18
8
10
11
22
https://www.geeksforgeeks.org/introduction-to-red-black-tree/
26
Max Heap #include<bits/stdc++.h>
using namespace std;
int main () {
int a[] = {2,4,8,9,7,10,9,15,20,13};
vector<int> v1(a, a+5);
vector<int> v2 = {2,4,8,9,7,10,9,15,20,13};
make_heap (v1.begin(), v1.end());
cout << "initial max heap : " << v.front() << 'n’;
pop_heap (v.begin(),v.end());
v.pop_back(); cout << "max heap after pop : " << v.front() << 'n’;
v.push_back(99);
push_heap (v.begin(),v.end());
cout << "max heap after push: " << v.front() << 'n’;
sort_heap (v.begin(),v.end());
cout << "final sorted range :";
for (unsigned i=0; i<v.size(); i++)
cout << ' ' << v[i]; cout << 'n’;
return 0;
}
16.
Min Heap #include<bits/stdc++.h>
using namespace std;
void print(vector<int> const& v = {}) {
for (const auto& e : v)
cout << e << ' ‘;
cout << 'n’;
}
int main () {
vector<int> v = {2,4,8,9,7,10,9,15,20,13};
print(v);
make_heap(v.begin(), v.end(), greater<>{});
pop_heap(v.begin(), v.end(), greater<>{});
auto top = v.back();
v.pop_back();
print({top});
print(v1);
return 0;
}
largestComponent() กลุ่มที่เชื่อมกันมากที่สุดกี่
จังหวัด
def largestComponent(graph):
largest= 0
visited = set()
for node in graph:
size = exploreSize(graph, node,
visited)
if size > largest: largest = size
return largest
def exploreSize(graph, node, visited):
if node in visited: return 0
visited.add(node)
size = 1
for neighbor of graph[node]:
size += exploreSize(graph, neighbor,
visited)
return size
100.
Exercise: W เป็นน้าL เป็นที่ดิน มีกี่เกาะ?
W L W W L W
L L W W L W
W L W W W W
W W W L L W
W L W L L W
W W W W W W
W L W W L W
L L W W L W
W L W W W W
W W W L L W
W L W L L W
W W W W W W
101.
Explore()
def explore(grid, r,c, visited):
if !(0 <= r < len(grid)) || !(0 <= c < len(grid[r])): return 0
if grid[r][c] == ‘W’: return 0
if (r,c) in visited: return 0
visited.add( (r,c) )
explore(grid, r-1, c, visited)
explore(grid, r+1, c, visited)
explore(grid, r, c-1, visited)
explore(grid, r, c+1, visited)
return 1
Exercise: W เป็นน้าL เป็นที่ดิน ที่ดินติดกัน
มากที่สุดกี่ช่อง?
W L W W L W
L L W W L W
W L W W W W
W W W L L W
W L W L L W
W W W W W W
W L W W L W
L L W W L W
W L W W W W
W W W L L W
W L W L L W
W W W W W W
Exercise: W เป็นน้าL เป็นที่ดิน ที่ดินติดกัน
น้อยที่สุดกี่ช่อง?
W L W W L W
L L W W L W
W L W W W W
W W W L L W
W L W L L W
W W W W W W
W L W W L W
L L W W L W
W L W W W W
W W W L L W
W L W L L W
W W W W W W