Skip to content

Commit ae2f995

Browse files
committed
cartesian and its document.
1 parent c91e671 commit ae2f995

2 files changed

Lines changed: 52 additions & 0 deletions

File tree

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
---
2+
title: Cartesian Tree Construction.
3+
documentation_of: ./src/alfred/data_structure/cartesian.hpp
4+
---
5+
6+
## Description
7+
8+
This module provides a function to build a Cartesian tree from a given vector in O(n) time. A Cartesian tree is a binary tree where each node's value is greater than the values of its children, and it is constructed based on the order of elements in the input vector.
9+
10+
## Usage Example
11+
12+
```cpp
13+
#include "cartesian.hpp"
14+
std::vector<int> a = {3, 1, 2};
15+
auto res = cartesian(a); // returns a vector of pairs representing ls and rs of each node.
16+
```
17+
18+
## Main Features
19+
- Supports custom comparison functions for building Cartesian trees based on different criteria.
20+
- Uses monostack algorithm, time complexity $O(n)$
21+
- Does not modify the original data (pass by value)
22+
23+
## Important Functions and Time Complexity
24+
25+
| Function | Description | Time Complexity |
26+
| ----------- | --------------------------------------------------------------------- | --------------- |
27+
| `cartesian` | Build a cartesian tree based on the given array and comparison method | $O(n)$ |
28+
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
#ifndef AFDS_CARTESIAN
2+
#define AFDS_CARTESIAN
3+
4+
#include <pair>
5+
#include <vector>
6+
7+
// Returns pair of (ls, rs).
8+
template <class T, class Comp = std::less<T>>
9+
std::vector<std::pair<int, int>> cartesian(std::vector<T> a, Comp comp) {
10+
std::vector<int> stk; // stack of right chain.
11+
std::vector<std::pair<int, int>> ans(a.size());
12+
for (size_t i = 0; i < a.size(); i++) {
13+
int lst = -1;
14+
while (!stk.empty() && comp(a[i], a[stk.back()])) {
15+
lst = stk.back(), stk.pop_back();
16+
}
17+
if (!stk.empty()) ans[stk.back()].second = i;
18+
if (lst != -1) ans[i].first = lst;
19+
stk.push_back(i);
20+
}
21+
return ans;
22+
}
23+
24+
#endif

0 commit comments

Comments
 (0)