Aleph-w 3.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
mo_algorithm_example.cc
Go to the documentation of this file.
1/*
2 Aleph_w
3
4 Data structures & Algorithms
5 version 2.0.0b
6 https://github.com/lrleon/Aleph-w
7
8 This file is part of Aleph-w library
9
10 Copyright (c) 2002-2026 Leandro Rabindranath Leon
11
12 Permission is hereby granted, free of charge, to any person obtaining a copy
13 of this software and associated documentation files (the "Software"), to deal
14 in the Software without restriction, including without limitation the rights
15 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16 copies of the Software, and to permit persons to whom the Software is
17 furnished to do so, subject to the following conditions:
18
19 The above copyright notice and this permission notice shall be included in all
20 copies or substantial portions of the Software.
21
22 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28 SOFTWARE.
29*/
30
31
57# include <tpl_mo_algorithm.H>
58# include <tpl_dynMapOhash.H>
59# include <tpl_dynSetHash.H>
60
61# include <algorithm>
62# include <cassert>
63# include <cstdio>
64
65using namespace Aleph;
66
67// ================================================================
68// Scenario 1: Biodiversity Survey
69// ================================================================
70
72{
73 printf("=== SCENARIO 1: Biodiversity Survey ===\n\n");
74 printf("A wildlife camera trap records species IDs over 12 hours.\n");
75 printf("We want to know how many distinct species appeared in each\n");
76 printf("time window.\n\n");
77
78 // Species IDs observed each hour (0-indexed)
79 // h0 h1 h2 h3 h4 h5 h6 h7 h8 h9 h10 h11
81 {3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8};
82
83 printf("Hour: ");
84 int data[] = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8};
85 for (int i = 0; i < 12; ++i)
86 printf("%3d", data[i]);
87 printf("\n\n");
88
89 // Queries: different time windows
90 auto ans = mo.solve({
91 {0, 3}, // early morning
92 {4, 8}, // midday
93 {0, 11}, // full day
94 {2, 5}, // late morning
95 {9, 11} // evening
96 });
97
98 printf("%-20s %s\n", "Time Window", "Distinct Species");
99 printf("%-20s %s\n", "-------------------", "----------------");
100 printf("%-20s %zu\n", "[h0, h3] morning", ans(0));
101 printf("%-20s %zu\n", "[h4, h8] midday", ans(1));
102 printf("%-20s %zu\n", "[h0, h11] full day", ans(2));
103 printf("%-20s %zu\n", "[h2, h5] late morn", ans(3));
104 printf("%-20s %zu\n", "[h9, h11] evening", ans(4));
105
106 // Verify against brute force
107 auto brute_distinct = [&](size_t l, size_t r) -> size_t {
109 for (size_t i = l; i <= r; ++i)
110 s.insert(data[i]);
111 return s.size();
112 };
113 assert(ans(0) == brute_distinct(0, 3));
114 assert(ans(1) == brute_distinct(4, 8));
115 assert(ans(2) == brute_distinct(0, 11));
116 assert(ans(3) == brute_distinct(2, 5));
117 assert(ans(4) == brute_distinct(9, 11));
118
119 printf("\nAll assertions passed!\n\n");
120}
121
122// ================================================================
123// Scenario 2: Powerful Array
124// ================================================================
125
126static void powerful_array()
127{
128 printf("=== SCENARIO 2: Powerful Array ===\n\n");
129 printf("Given array a[], for a range [l,r] compute:\n");
130 printf(" sum over distinct x in a[l..r] of cnt(x)^2 * x\n\n");
131
132 // 0 1 2 3 4 5
133 const Powerful_Array_Mo<int> mo = {1, 2, 1, 1, 2, 3};
134
135 printf("Array: [1, 2, 1, 1, 2, 3]\n\n");
136
137 auto ans = mo.solve({
138 {0, 0}, // {1:1} => 1
139 {0, 2}, // {1:2, 2:1} => 4*1 + 1*2 = 6
140 {0, 5}, // {1:3, 2:2, 3:1} => 9*1 + 4*2 + 1*3 = 20
141 {3, 5}, // {1:1, 2:1, 3:1} => 1+2+3 = 6
142 {1, 4} // {2:2, 1:2} => 4*2 + 4*1 = 12
143 });
144
145 printf("%-15s %s\n", "Range", "Power");
146 printf("%-15s %s\n", "-----------", "-----");
147 printf("%-15s %lld\n", "[0,0]", ans(0));
148 printf("%-15s %lld\n", "[0,2]", ans(1));
149 printf("%-15s %lld\n", "[0,5]", ans(2));
150 printf("%-15s %lld\n", "[3,5]", ans(3));
151 printf("%-15s %lld\n", "[1,4]", ans(4));
152
153 assert(ans(0) == 1LL);
154 assert(ans(1) == 6LL);
155 assert(ans(2) == 20LL);
156 assert(ans(3) == 6LL);
157 assert(ans(4) == 12LL);
158
159 printf("\nAll assertions passed!\n\n");
160}
161
162// ================================================================
163// Scenario 3: Election Polling
164// ================================================================
165
166static void election_polling()
167{
168 printf("=== SCENARIO 3: Election Polling ===\n\n");
169 printf("Voters report their preferred candidate (1-4) over time.\n");
170 printf("Find the most popular candidate in each polling window.\n\n");
171
172 // Candidate IDs reported by voters over time
173 // v0 v1 v2 v3 v4 v5 v6 v7 v8 v9
174 Range_Mode_Mo<int> mo = {2, 3, 2, 1, 2, 3, 3, 1, 4, 3};
175
176 printf("Voter: ");
177 int data[] = {2, 3, 2, 1, 2, 3, 3, 1, 4, 3};
178 for (int i = 0; i < 10; ++i)
179 printf("%3d", data[i]);
180 printf("\n\n");
181
182 auto ans = mo.solve({
183 {0, 9}, // all voters
184 {0, 4}, // first half
185 {5, 9}, // second half
186 {2, 6} // middle window
187 });
188
189 printf("%-20s %-10s %s\n", "Window", "Freq", "Candidate");
190 printf("%-20s %-10s %s\n", "-------------------", "----", "---------");
191
192 const char * labels[] = {"[v0,v9] all", "[v0,v4] first",
193 "[v5,v9] second", "[v2,v6] middle"};
194 for (size_t i = 0; i < 4; ++i)
195 printf("%-20s %-10zu %d\n", labels[i], ans(i).first, ans(i).second);
196
197 // Verify frequencies via brute force
198 auto brute_freq = [&](size_t l, size_t r) -> size_t {
200 for (size_t i = l; i <= r; ++i)
201 ++freq[data[i]];
202
203 size_t mx = 0;
204 for (MapOLhash<int, size_t>::Iterator it(freq); it.has_curr(); it.next_ne())
205 mx = std::max(mx, it.get_curr().second);
206
207 return mx;
208 };
209 assert(ans(0).first == brute_freq(0, 9));
210 assert(ans(1).first == brute_freq(0, 4));
211 assert(ans(2).first == brute_freq(5, 9));
212 assert(ans(3).first == brute_freq(2, 6));
213
214 printf("\nAll assertions passed!\n\n");
215}
216
217// ================================================================
218// Scenario 4: Custom Policy — Network Packet Analysis
219// ================================================================
220
223{
224 using answer_type = long long;
225
226 long long sum_sq = 0;
227
228 void init(const Array<int> &, size_t) { sum_sq = 0; }
229
230 void add(const Array<int> & data, size_t idx)
231 {
232 long long x = data(idx);
233 sum_sq += x * x;
234 }
235
236 void remove(const Array<int> & data, size_t idx)
237 {
238 long long x = data(idx);
239 sum_sq -= x * x;
240 }
241
242 answer_type answer() const { return sum_sq; }
243};
244
246{
247 printf("=== SCENARIO 4: Custom Policy — Network Packet Analysis ===\n\n");
248 printf("Packet sizes (bytes) captured over 10 time slots.\n");
249 printf("Query: sum of squared sizes in each window (for variance\n");
250 printf("analysis / anomaly detection).\n\n");
251
252 // Packet sizes (in hundreds of bytes)
254 {15, 8, 22, 3, 17, 11, 9, 25, 6, 14};
255
256 int data[] = {15, 8, 22, 3, 17, 11, 9, 25, 6, 14};
257
258 printf("Slot: ");
259 for (int i = 0; i < 10; ++i)
260 printf("%5d", data[i]);
261 printf("\n\n");
262
263 auto ans = mo.solve({
264 {0, 9}, // all
265 {0, 4}, // first half
266 {5, 9}, // second half
267 {2, 7} // burst window
268 });
269
270 printf("%-20s %s\n", "Window", "Sum of Squares");
271 printf("%-20s %s\n", "-------------------", "--------------");
272
273 const char * labels[] = {"[0,9] all", "[0,4] first",
274 "[5,9] second", "[2,7] burst"};
275 for (size_t i = 0; i < 4; ++i)
276 printf("%-20s %lld\n", labels[i], ans(i));
277
278 // Verify via brute force
279 auto brute_ssq = [&](size_t l, size_t r) -> long long {
280 long long s = 0;
281 for (size_t i = l; i <= r; ++i)
282 s += (long long)data[i] * data[i];
283 return s;
284 };
285
286 assert(ans(0) == brute_ssq(0, 9));
287 assert(ans(1) == brute_ssq(0, 4));
288 assert(ans(2) == brute_ssq(5, 9));
289 assert(ans(3) == brute_ssq(2, 7));
290
291 printf("\nAll assertions passed!\n\n");
292}
293
294// ================================================================
295// Main
296// ================================================================
297
298int main()
299{
300 printf("Mo's Algorithm — Offline Range Queries\n");
301 printf("======================================\n\n");
302
307
308 printf("All scenarios completed successfully.\n");
309 return 0;
310}
Simple dynamic array with automatic resizing and functional operations.
Definition tpl_array.H:139
Self-adjusting dynamic hash table.
Key * insert(const Key &key)
Inserts key into the hash set.
Offline range query engine using Mo's algorithm.
static void biodiversity_survey()
static void network_packet_analysis()
static void election_polling()
static void powerful_array()
int main()
Main namespace for Aleph-w library functions.
Definition ah-arena.H:89
Divide_Conquer_DP_Result< Cost > divide_and_conquer_partition_dp(const size_t groups, const size_t n, Transition_Cost_Fn transition_cost, const Cost inf=dp_optimization_detail::default_inf< Cost >())
Optimize partition DP using divide-and-conquer optimization.
Open addressing hash map using linear probing.
Custom Mo policy: sum of squared packet sizes in a window.
answer_type answer() const
void init(const Array< int > &, size_t)
void add(const Array< int > &data, size_t idx)
void remove(const Array< int > &data, size_t idx)
gsl_rng * r
Dynamic map with open hashing.
Dynamic set implementations based on hash tables.
Mo's algorithm for offline range queries.
DynList< int > l