Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
tpl_mo_algorithm.H
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
64# ifndef TPL_MO_ALGORITHM_H
65# define TPL_MO_ALGORITHM_H
66
67# include <algorithm>
68# include <cmath>
69# include <concepts>
70# include <type_traits>
71# include <utility>
72# include <tpl_array.H>
73# include <tpl_dynMapOhash.H>
74# include <tpl_dynList.H>
75# include <tpl_sort_utils.H>
76# include <ah-errors.H>
77
78namespace Aleph
79{
83 struct Mo_Query
84 {
85 size_t l;
86 size_t r;
87 size_t id;
88 };
89
103 template <typename P, typename T>
104 concept MoPolicy = requires(P & p, const Array<T> & data,
105 size_t idx, size_t n)
106 {
107 typename P::answer_type;
108 { p.init(data, n) };
109 { p.add(data, idx) };
110 { p.remove(data, idx) };
111 { p.answer() } -> std::convertible_to<typename P::answer_type>;
112 };
113
114 // ================================================================
115 // Gen_Mo_Algorithm — Offline range queries via Mo's algorithm
116 // ================================================================
117
140 template <typename T, class Policy>
141 requires MoPolicy<Policy, T>
143 {
145 mutable Policy pol_;
146
147 public:
148 using Item_Type = T;
149 using answer_type = typename Policy::answer_type;
150
162 Gen_Mo_Algorithm(std::initializer_list<T> il, Policy p = Policy())
163 : data_(il), pol_(std::move(p))
164 {}
165
177 Gen_Mo_Algorithm(const Array<T> & arr, Policy p = Policy())
178 : data_(arr), pol_(std::move(p))
179 {}
180
192 Gen_Mo_Algorithm(Array<T> and arr, Policy p = Policy())
193 : data_(std::move(arr)), pol_(std::move(p))
194 {}
195
207 Gen_Mo_Algorithm(const DynList<T> & lst, Policy p = Policy())
208 : data_(Array<T>::create(lst.size())), pol_(std::move(p))
209 {
210 size_t i = 0;
211 for (auto it = lst.get_it(); it.has_curr(); it.next_ne())
212 data_(i++) = it.get_curr();
213 }
214
216
218 std::is_nothrow_move_constructible_v<Array<T>> and
219 std::is_nothrow_move_constructible_v<Policy>) = default;
220
221 Gen_Mo_Algorithm &operator=(const Gen_Mo_Algorithm &) = default;
222
223 Gen_Mo_Algorithm &operator=(Gen_Mo_Algorithm &&) noexcept(
224 std::is_nothrow_move_assignable_v<Array<T>> and
225 std::is_nothrow_move_assignable_v<Policy>) = default;
226
228 [[nodiscard]] constexpr size_t size() const noexcept
229 {
230 return data_.size();
231 }
232
234 [[nodiscard]] constexpr bool is_empty() const noexcept
235 {
236 return data_.size() == 0;
237 }
238
240 void swap(Gen_Mo_Algorithm & other) noexcept(
241 noexcept(std::swap(std::declval<Policy &>(), std::declval<Policy &>())))
242 {
243 data_.swap(other.data_);
244 std::swap(pol_, other.pol_);
245 }
246
266 Array<answer_type> solve(const Array<std::pair<size_t, size_t>> & ranges) const
267 {
268 auto queries = Array<Mo_Query>::create(ranges.size());
269 for (size_t i = 0; i < ranges.size(); ++i)
270 queries(i) = {ranges(i).first, ranges(i).second, i};
271 return solve(queries);
272 }
273
290 Array<answer_type> solve(const std::initializer_list<std::pair<size_t, size_t>> il) const
291 {
292 const Array<std::pair<size_t, size_t>> ranges(il);
293 return solve(ranges);
294 }
295
319 {
320 const size_t n = data_.size();
321 const size_t q = queries.size();
322
323 if (q == 0)
324 return Array<answer_type>();
325
326 // Validate all queries
327 for (size_t i = 0; i < q; ++i)
328 {
329 ah_out_of_range_error_if(queries(i).r >= n)
330 << "Gen_Mo_Algorithm::solve: query " << i
331 << " r=" << queries(i).r << " >= n=" << n;
332 ah_out_of_range_error_if(queries(i).l > queries(i).r)
333 << "Gen_Mo_Algorithm::solve: query " << i
334 << " l=" << queries(i).l << " > r=" << queries(i).r;
335 ah_out_of_range_error_if(queries(i).id >= q)
336 << "Gen_Mo_Algorithm::solve: query " << i
337 << " id=" << queries(i).id << " >= q=" << q;
338 }
339
340 const size_t block = std::max<size_t>(1, static_cast<size_t>(std::sqrt(static_cast<double>(n))));
341
342 // Snake sort: primary by l/block, secondary alternating by r
343 introsort(queries,
344 [block](const Mo_Query & a, const Mo_Query & b)
345 {
346 const size_t ba = a.l / block;
347 const size_t bb = b.l / block;
348 if (ba != bb)
349 return ba < bb;
350 // Even blocks: r ascending; odd blocks: r descending
351 return (ba & 1) ? (a.r > b.r) : (a.r < b.r);
352 });
353
354 pol_.init(data_, n);
355
356 auto answers = Array<answer_type>::create(q);
357
358 // Initialise a window to the first query
359 size_t cur_l = queries(0).l;
360 size_t cur_r = queries(0).l;
361 pol_.add(data_, cur_l);
362
363 // Expand to the first query's right endpoint
364 while (cur_r < queries(0).r)
365 pol_.add(data_, ++cur_r);
366
367 answers(queries(0).id) = pol_.answer();
368
369 // Sweep remaining queries
370 for (size_t i = 1; i < q; ++i)
371 {
372 const size_t ql = queries(i).l;
373 const size_t qr = queries(i).r;
374
375 // Expand right
376 while (cur_r < qr)
377 pol_.add(data_, ++cur_r);
378
379 // Expand left
380 while (cur_l > ql)
381 pol_.add(data_, --cur_l);
382
383 // Shrink right
384 while (cur_r > qr)
385 pol_.remove(data_, cur_r--);
386
387 // Shrink left
388 while (cur_l < ql)
389 pol_.remove(data_, cur_l++);
390
391 answers(queries(i).id) = pol_.answer();
392 }
393
394 return answers;
395 }
396 };
397
398 // ================================================================
399 // Built-in policies
400 // ================================================================
401
411 template <typename T>
413 {
414 using answer_type = size_t;
415
417 size_t distinct = 0;
418
419 void init(const Array<T> &, size_t)
420 {
422 freq.swap(tmp);
423 distinct = 0;
424 }
425
426 void add(const Array<T> & data, size_t idx)
427 {
428 if (++freq[data(idx)] == 1)
429 ++distinct;
430 }
431
432 void remove(const Array<T> & data, size_t idx)
433 {
434 if (--freq[data(idx)] == 0)
435 --distinct;
436 }
437
438 [[nodiscard]] answer_type answer() const { return distinct; }
439 };
440
452 template <typename T>
454 {
455 using answer_type = long long;
456
458 long long sum = 0;
459
460 void init(const Array<T> &, size_t)
461 {
463 cnt.swap(tmp);
464 sum = 0;
465 }
466
467 void add(const Array<T> & data, size_t idx)
468 {
469 const auto x = static_cast<long long>(data(idx));
470 sum += (2 * cnt[data(idx)] + 1) * x;
471 ++cnt[data(idx)];
472 }
473
474 void remove(const Array<T> & data, size_t idx)
475 {
476 const auto x = static_cast<long long>(data(idx));
477 --cnt[data(idx)];
478 sum -= (2 * cnt[data(idx)] + 1) * x;
479 }
480
481 [[nodiscard]] answer_type answer() const { return sum; }
482 };
483
498 template <typename T>
500 {
501 using answer_type = std::pair<size_t, T>;
502
505 size_t max_freq = 0;
507
508 void init(const Array<T> &, size_t)
509 {
510 MapOLhash<T, size_t> tmp_freq;
512 freq.swap(tmp_freq);
513 cnt_of_cnt.swap(tmp_cnt);
514 max_freq = 0;
515 mode_val = T();
516 }
517
518 void add(const Array<T> & data, size_t idx)
519 {
520 const T & x = data(idx);
521 const size_t old_f = freq[x];
522 if (old_f > 0)
523 --cnt_of_cnt[old_f];
524 ++freq[x];
525 ++cnt_of_cnt[old_f + 1];
526 if (old_f + 1 > max_freq)
527 {
528 max_freq = old_f + 1;
529 mode_val = x;
530 }
531 }
532
533 void remove(const Array<T> & data, size_t idx)
534 {
535 const T & x = data(idx);
536 const size_t old_f = freq[x];
537 --cnt_of_cnt[old_f];
538 if (old_f > 1)
539 ++cnt_of_cnt[old_f - 1];
540 --freq[x];
541 if (old_f == max_freq and cnt_of_cnt[old_f] == 0)
542 {
543 --max_freq;
544 // Find a value with the new max frequency; if max_freq is 0,
545 // the window is empty.
546 if (max_freq > 0)
547 {
548 for (typename MapOLhash<T, size_t>::Iterator it(freq);
549 it.has_curr(); it.next_ne())
550 if (it.get_curr().second == max_freq)
551 {
552 mode_val = it.get_curr().first;
553 break;
554 }
555 }
556 }
557 else if (old_f == max_freq and x == mode_val)
558 {
559 // x was the mode, but other elements still share max_freq;
560 // pick any one of them.
561 for (typename MapOLhash<T, size_t>::Iterator it(freq);
562 it.has_curr(); it.next_ne())
563 if (it.get_curr().second == max_freq)
564 {
565 mode_val = it.get_curr().first;
566 break;
567 }
568 }
569 }
570
571 answer_type answer() const { return {max_freq, mode_val}; }
572 };
573
574 // ================================================================
575 // Convenient typedefs
576 // ================================================================
577
582 template <typename T>
584
589 template <typename T>
591
596 template <typename T>
598} // namespace Aleph
599
600# endif // TPL_MO_ALGORITHM_H
Exception handling system with formatted messages for Aleph-w.
#define ah_out_of_range_error_if(C)
Throws std::out_of_range if condition holds.
Definition ah-errors.H:727
Simple dynamic array with automatic resizing and functional operations.
Definition tpl_array.H:141
constexpr size_t size() const noexcept
Return the number of elements stored in the stack.
Definition tpl_array.H:450
static Array create(const size_t n)
Create an array with n logical elements.
Definition tpl_array.H:245
Doubly-linked list (defined in tpl_dynList.H).
Definition htlist.H:1231
Offline range query engine using Mo's algorithm.
Array< answer_type > solve(Array< Mo_Query > queries) const
Core solver: answer all Mo_Query objects.
Array< answer_type > solve(const std::initializer_list< std::pair< size_t, size_t > > il) const
Solve queries given as (l, r) pairs (initializer list).
Gen_Mo_Algorithm(Gen_Mo_Algorithm &&) noexcept(std::is_nothrow_move_constructible_v< Array< T > > and std::is_nothrow_move_constructible_v< Policy >)=default
Gen_Mo_Algorithm(Array< T > and arr, Policy p=Policy())
Construct from an Array<T> (move).
Gen_Mo_Algorithm(const DynList< T > &lst, Policy p=Policy())
Construct from a DynList<T>.
constexpr bool is_empty() const noexcept
True if the data array is empty.
Array< answer_type > solve(const Array< std::pair< size_t, size_t > > &ranges) const
Solve queries given as (l, r) pairs.
void swap(Gen_Mo_Algorithm &other) noexcept(noexcept(std::swap(std::declval< Policy & >(), std::declval< Policy & >())))
Swap with other in O(1).
Gen_Mo_Algorithm(std::initializer_list< T > il, Policy p=Policy())
Construct from an initializer list.
constexpr size_t size() const noexcept
Number of elements in the data array.
typename Policy::answer_type answer_type
Gen_Mo_Algorithm(const Array< T > &arr, Policy p=Policy())
Construct from an Array<T>.
Gen_Mo_Algorithm(const Gen_Mo_Algorithm &)=default
auto get_it()
Return a properly initialized iterator positioned at the first item on the container.
Definition ah-dry.H:663
Concept constraining a policy for Mo's algorithm.
pair< size_t, string > P
Main namespace for Aleph-w library functions.
std::decay_t< typename HeadC::Item_Type > T
Definition ah-zip.H:152
and
Check uniqueness with explicit hash + equality functors.
void introsort(T *a, const long l, const long r, const Compare &cmp=Compare())
Sort an array using introsort (introspective sort).
STL namespace.
Policy: count distinct elements in a range.
void add(const Array< T > &data, size_t idx)
void remove(const Array< T > &data, size_t idx)
MapOLhash< T, size_t > freq
void init(const Array< T > &, size_t)
Open addressing hash map using linear probing.
typename Base::Iterator Iterator
Iterator type for traversing the map.
A query for Mo's algorithm: inclusive range [l, r] with id.
size_t id
Original query index (for reordering answers).
size_t l
Left endpoint (inclusive, 0-based).
size_t r
Right endpoint (inclusive, 0-based).
Policy: "powerful array" sum = sum(cnt[x]^2 * x).
void init(const Array< T > &, size_t)
void remove(const Array< T > &data, size_t idx)
void add(const Array< T > &data, size_t idx)
MapOLhash< T, long long > cnt
Policy: range mode (most frequent element).
void remove(const Array< T > &data, size_t idx)
std::pair< size_t, T > answer_type
MapOLhash< T, size_t > freq
void init(const Array< T > &, size_t)
answer_type answer() const
void add(const Array< T > &data, size_t idx)
MapOLhash< size_t, size_t > cnt_of_cnt
Gsl_Compatible_Rng r
Dynamic array container with automatic resizing.
Alias for htlist.H (DynList implementation).
Dynamic map with open hashing.
Comprehensive sorting algorithms and search utilities for Aleph-w.
DynList< int > l