Inkscape
Vector Graphics Editor
Loading...
Searching...
No Matches
longest-common-suffix.h
Go to the documentation of this file.
1// SPDX-License-Identifier: GPL-2.0-or-later
2/*
3 * Inkscape::Algorithms::nearest_common_ancestor
4 *
5 * Authors:
6 * MenTaLguY <mental@rydia.net>
7 *
8 * Copyright (C) 2004 MenTaLguY
9 *
10 * Released under GNU GPL v2+, read the file 'COPYING' for more information.
11 */
12
13#ifndef SEEN_INKSCAPE_ALGORITHMS_NEAREST_COMMON_ANCESTOR_H
14#define SEEN_INKSCAPE_ALGORITHMS_NEAREST_COMMON_ANCESTOR_H
15
16#include <iterator>
17#include <functional>
18
19namespace Inkscape {
20
21namespace Algorithms {
22
33template <typename ForwardIterator>
34ForwardIterator nearest_common_ancestor(ForwardIterator a, ForwardIterator b, ForwardIterator end)
35{
36 if ( a == end || b == end ) {
37 return end;
38 }
39
40 /* Handle in O(1) time the common cases of identical lists or tails. */
41 {
42 /* identical lists? */
43 if ( a == b ) {
44 return a;
45 }
46
47 /* identical tails? */
48 ForwardIterator tail_a(a);
49 ForwardIterator tail_b(b);
50 if ( ++tail_a == ++tail_b ) {
51 return tail_a;
52 }
53 }
54
55 /* Build parallel lists of suffixes, ordered by increasing length. */
56
57 ForwardIterator lists[2] = { a, b };
58 std::vector<ForwardIterator> suffixes[2];
59
60 for ( int i=0 ; i < 2 ; i++ ) {
61 for ( ForwardIterator iter(lists[i]) ; iter != end ; ++iter ) {
62 if ( iter == lists[1-i] ) {
63 // the other list is a suffix of this one
64 return lists[1-i];
65 }
66 suffixes[i].push_back(iter);
67 }
68 }
69
70 /* Iterate in parallel through the lists of suffix lists from shortest to
71 * longest, stopping before the first pair of suffixes that differs
72 */
73
74 ForwardIterator longest_common(end);
75
76 while ( !suffixes[0].empty() && !suffixes[1].empty() &&
77 suffixes[0].back() == suffixes[1].back() )
78 {
79 longest_common = suffixes[0].back();
80 suffixes[0].pop_back();
81 suffixes[1].pop_back();
82 }
83
84 return longest_common;
85}
86
87}
88
89}
90
91#endif /* !SEEN_INKSCAPE_ALGORITHMS_NEAREST_COMMON_ANCESTOR_H */
92
93/*
94 Local Variables:
95 mode:c++
96 c-file-style:"stroustrup"
97 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
98 indent-tabs-mode:nil
99 fill-column:99
100 End:
101*/
102// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :
Geom::Point end
ForwardIterator nearest_common_ancestor(ForwardIterator a, ForwardIterator b, ForwardIterator end)
Time costs:
Helper class to stream background task notifications as a series of messages.