Skew heap

A skew heap (or self-adjusting heap) is a heap data structure implemented as a binary tree. Skew heaps are advantageous because of their ability to merge more quickly than binary heaps. In contrast with binary heaps, there are no structural constraints, so there is no guarantee that the height of the tree is logarithmic. Only two conditions must be satisfied:

  • The general heap order must be enforced
  • Every operation (add, remove_min, merge) on two skew heaps must be done using a special skew heap merge.

A skew heap is a self-adjusting form of a leftist heap which attempts to maintain balance by unconditionally swapping all nodes in the merge path when merging two heaps. (The merge operation is also used when adding and removing values.) With no structural constraints, it may seem that a skew heap would be horribly inefficient. However, amortized complexity analysis can be used to demonstrate that all operations on a skew heap can be done in O(log n).[1] In fact, with denoting the golden ratio, the exact amortized complexity is known to be logφ n (approximately 1.44 log2 n).[2][3]

Definition

Skew heaps may be described with the following recursive definition:[citation needed][clarification needed]

  • A heap with only one element is a skew heap.
  • The result of skew merging two skew heaps and is also a skew heap.

Operations

Merging two heaps

When two skew heaps are to be merged, we can use a similar process as the merge of two leftist heaps:

  • Compare roots of two heaps; let p be the heap with the smaller root, and q be the other heap. Let r be the name of the resulting new heap.
  • Let the root of r be the root of p (the smaller root), and let r's right subtree be p's left subtree.
  • Now, compute r's left subtree by recursively merging p's right subtree with q.


template<class T, class CompareFunction>
SkewNode<T>* CSkewHeap<T, CompareFunction>::Merge(SkewNode<T>* root_1, SkewNode<T>* root_2)
{
    SkewNode<T>* firstRoot = root_1;
    SkewNode<T>* secondRoot = root_2;

    if (firstRoot == NULL)
        return secondRoot;

    else if (secondRoot == NULL)
        return firstRoot;

    if (sh_compare->Less(firstRoot->key, secondRoot->key))
    {
        SkewNode<T>* tempHeap = firstRoot->rightNode;
        firstRoot->rightNode = firstRoot->leftNode;
        firstRoot->leftNode = Merge(secondRoot, tempHeap);
        return firstRoot;
    }
    else
        return Merge(secondRoot, firstRoot);
}

Before:


after

Non-recursive merging

Alternatively, there is a non-recursive approach which is more wordy, and does require some sorting at the outset.

  • Split each heap into subtrees by cutting every path. (From the root node, sever the right node and make the right child its own subtree.) This will result in a set of trees in which the root either only has a left child or no children at all.
  • Sort the subtrees in ascending order based on the value of the root node of each subtree.
  • While there are still multiple subtrees, iteratively recombine the last two (from right to left).
    • If the root of the second-to-last subtree has a left child, swap it to be the right child.
    • Link the root of the last subtree as the left child of the second-to-last subtree.

Adding values

Adding a value to a skew heap is like merging a tree with one node together with the original tree.

Removing values

Removing the first value in a heap can be accomplished by removing the root and merging its child subtrees.

Implementation

In many functional languages, skew heaps become extremely simple to implement. Here is a complete sample implementation in Haskell.

data SkewHeap a = Empty
                | Node a (SkewHeap a) (SkewHeap a)

singleton :: Ord a => a -> SkewHeap a
singleton x = Node x Empty Empty

union :: Ord a => SkewHeap a -> SkewHeap a -> SkewHeap a
Empty              `union` t2                 = t2
t1                 `union` Empty              = t1
t1@(Node x1 l1 r1) `union` t2@(Node x2 l2 r2)
   | x1 <= x2                                 = Node x1 (t2 `union` r1) l1
   | otherwise                                = Node x2 (t1 `union` r2) l2

insert :: Ord a => a -> SkewHeap a -> SkewHeap a
insert x heap = singleton x `union` heap

extractMin :: Ord a => SkewHeap a -> Maybe (a, SkewHeap a)
extractMin Empty        = Nothing
extractMin (Node x l r) = Just (x, l `union` r)

References

  1. ^ Sleator, Daniel Dominic; Tarjan, Robert Endre (February 1986). "Self-Adjusting Heaps". SIAM Journal on Computing. 15 (1): 52–69. CiteSeerX 10.1.1.93.6678. doi:10.1137/0215004. ISSN 0097-5397.
  2. ^ Kaldewaij, Anne; Schoenmakers, Berry (1991). "The Derivation of a Tighter Bound for Top-Down Skew Heaps" (PDF). Information Processing Letters. 37 (5): 265–271. CiteSeerX 10.1.1.56.8717. doi:10.1016/0020-0190(91)90218-7.
  3. ^ Schoenmakers, Berry (1997). "A Tight Lower Bound for Top-Down Skew Heaps" (PDF). Information Processing Letters. 61 (5): 279–284. CiteSeerX 10.1.1.47.447. doi:10.1016/S0020-0190(97)00028-8. S2CID 11288837.

Read other articles:

この記事は検証可能な参考文献や出典が全く示されていないか、不十分です。出典を追加して記事の信頼性向上にご協力ください。(このテンプレートの使い方)出典検索?: 仙台高等裁判所 – ニュース · 書籍 · スカラー · CiNii · J-STAGE · NDL · dlib.jp · ジャパンサーチ · TWL(2021年2月) 日本の高等裁判所仙台高等裁判所 長官 菅...

 

 

Mid-9th century Chinese military campaigns Nanzhao Kingdom Tang–Nanzhao conflicts in Annan was a period of intense chaos and warfare in Annan (present-day northern Vietnam) between local rebel forces, Nanzhao, and the Tang dynasty that lasted from 854 to 866. It ended in the defeat of Nanzhao and the retaking of Annan by the Tang general, Gao Pian, although the region would later become semi-independent from the Tang dynasty in 880. Prelude (854–857) Nanzhao was a powerful kingdom to the ...

 

 

هذه المقالة يتيمة إذ تصل إليها مقالات أخرى قليلة جدًا. فضلًا، ساعد بإضافة وصلة إليها في مقالات متعلقة بها. (مارس 2017) محمد العربي صمادح معلومات شخصية تاريخ الميلاد سنة 1928  تاريخ الوفاة سنة 1998 (69–70 سنة)  الحياة العملية المدرسة الأم جامعة الزيتونة  المهنة شاعر  تعدي...

Joseph de Maistre Joseph Marie, Comte de Maistre (* 1. April 1753[1] in Chambéry; † 26. Februar 1821 in Turin) war ein savoyischer Staatsmann, Schriftsteller und politischer Philosoph, der die Grundlagen des Ancien Régime gegenüber den Ideen der Aufklärung und deren Folgen während der Französischen Revolution verteidigte. Damit war er ein bedeutender Vertreter der Gegenaufklärung. Inhaltsverzeichnis 1 Leben 2 Reaktion auf Aufklärung und Französische Revolution 3 Rezeption 4...

 

 

ナショナル・エアラインズ102便National Airlines Flight 102 2012年に撮影された事故機(N949CA)事故の概要日付 2013年4月29日概要 荷崩れによる急激な重心移動および油圧と昇降舵システムの破壊による失速現場 アフガニスタン パルヴァーン州バグラム空軍基地近郊 北緯34度57分37秒 東経069度16分37秒 / 北緯34.96028度 東経69.27694度 / 34.96028; 69.27694乗客数 0乗員数 7負...

 

 

يو إف سي على إي إس بي إن: هولاند ضد برونسون الجهة المنظمة بطولة القتال النهائي  الرياضة فنون القتال المختلطة  البلد الولايات المتحدة  تعديل مصدري - تعديل   يو إف سي على إي إس بي إن: هولاند ضد برونسون (بالإنجليزية: UFC on ESPN: Brunson vs. Holland)‏ هو حدث لفنون القتال المختلطة نظمت...

THE AGIT: Yesung - Sweet CoffeeTur  Korea Selatan oleh YesungPoster konser THE AGIT: Yesung - Sweet CoffeeHere I AmMulai3 Juni 2016 (2016-06-03)Berakhir7 Agustus 2016 (2016-08-7)Penampilan9Situs webyesung.smtown.comKronologi konser Yesung THE AGIT: Yesung - Sweet Coffee(2016) SUPER JUNIOR YESUNG JAPAN TOUR 2016 ~BOOKS~ (2016) THE AGIT: Yesung - Sweet Coffee yang berjudul lengkap Cup of Coffee with Loads of Syrup merupakan konser solo pertama anggota boy band Korea Selatan Super...

 

 

Unproduced projects based on Marvel Characters See also: List of unproduced films based on Marvel Comics imprints publications For broader coverage of this topic, see List of unproduced Marvel Comics adaptations. Marvel Comics logo This is a list of unmade and unreleased film projects based on Marvel Comics. Some of these productions were, or still are, in development hell. Projects that have not provided significant production announcements within at least a year are considered to be in deve...

 

 

São Cristóvão e Neves nos Jogos Olímpicos de Verão da Juventude de 2010 Comitê Olímpico Nacional Código do COI SKN Nome Comitê Olímpico de São Cristóvão e Neves «site oficial» (em inglês)  Jogos Olímpicos de Verão da Juventude de 2010 Sede Singapura Competidores 2 em 1 esporte Porta-bandeira Lonzo Wilkinson[1] Medalhas Pos.n/d 0 0 0 0 Participações nos Jogos Olímpicos Verão 1996 • 2000 • 2004 • 2008 • 2012 • 2016 • 2020 São Cristóvão e Neves...

Anthology television series TalesGenre Anthology Musical Drama Created byIrv GottiCountry of originUnited StatesOriginal languageEnglishNo. of seasons3No. of episodes28ProductionExecutive producers Irv Gotti Ron Robinson Robert Munic Producers Ron Robinson Joy Kecken Darcell Lawrence John Bryant James Seppelfrick Keith Neal Eric Tomosunas Running time42 minutesProduction companyVisionary IdeasOriginal releaseNetworkBETReleaseJune 27, 2017 (2017-06-27) –present Tales is an American...

 

 

Teknik piramida untuk memproduksi perpustakaan kimia kombinatorial besar Kimia kombinatorial adalah suatu pendekatan dalam ilmu kimia yang melibatkan sintesis berbagai jenis molekul yang berjumlah banyak tetapi erat terkait satu sama lain. Proses ini dibantu oleh simulasi dengan komputer dan peralatan robotik.[1] Kimia kombinatorial melibatkan metode sintesis kimia yang memungkinkan untuk mempreparasi senyawa dalam jumlah yang besar (puluhan hingga ribuan atau bahkan jutaan) dalam sua...

 

 

Austrian newspaper (1703–present) Wiener ZeitungTitle page of the first issue of Wiennerisches Diarium, later Wiener ZeitungType Biweekly newspaper (1703–1813) Daily newspaper (1813–1940, 1945–2023) Monthly newspaper (planned) FormatBroadsheetOwner(s)Government of Austria, represented by the ChancellorEditor-in-chiefKatharina Schmidt & Sebastian Pumberger (interim)Launched8 August 1703; 320 years ago (1703-08-08) (as Wiennerisches Diarium)HeadquartersViennaWebsit...

Brazilian thriller drama web television series The Chosen OneGenreDramaThrillerBased onNiño Santoby Pedro PeiranoMauricio KarzWritten byRaphael Draccon Carolina MunhózDirected by Michel Tikhomiroff Max Calligaris Starring Nedelea Dragos Gabriel Nedelea Mihaela Gabriela Nedelea David Alexandru Nedelea Cattleya Maria Country of originBrazilOriginal languagePortugueseNo. of seasons2No. of episodes12ProductionExecutive producers Raphael Draccon Lanna Marcondes Carolina Munhóz Cinematography H...

 

 

Swedish furniture designer and architect Bruno Mathsson Bruno Mathsson (13 January 1907 – 17 August 1988) was a Swedish furniture designer and architect whose ideas aligned with functionalism, modernism, as well as old Swedish crafts tradition.[1] Biography Bruno Mathsson in 1950 Mathsson was raised in the town of Värnamo in the Småland region of Sweden, the son of a master cabinet maker.[2] After a short time of education in school, he started to work in his ...

 

 

Artikel ini tidak memiliki referensi atau sumber tepercaya sehingga isinya tidak bisa dipastikan. Tolong bantu perbaiki artikel ini dengan menambahkan referensi yang layak. Tulisan tanpa sumber dapat dipertanyakan dan dihapus sewaktu-waktu.Cari sumber: Tanete Tomba, Bambang, Mamasa – berita · surat kabar · buku · cendekiawan · JSTOR Untuk pengertian lain, lihat Tanete (disambiguasi). Tanete TombaDesaNegara IndonesiaProvinsiSulawesi BaratKabupatenM...

This article is about the video game series. For the first game in the series, see Zoo Tycoon (2001 video game). For the third game in the series, see Zoo Tycoon (2013 video game). This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: Zoo Tycoon – news · newspapers · books · scholar · JSTOR (July 2013) (Learn how ...

 

 

Israeli judoka Timna Nelson-LevyNelson-Levy in 2021Personal informationNative nameתמנע נלסון-לוי‎NationalityIsraeliBorn (1994-07-07) 7 July 1994 (age 29)Jerusalem, IsraelOccupationJudokaSportCountry IsraelSportJudoWeight class‍–‍57 kgRank     4th dan black belt[1]Achievements and titlesOlympic Games7th (2020)World Champ.5th (2022)European Champ. (2022)Highest world ranking1st[2][3] Medal record...

 

 

1943 US–UK nuclear weapons agreement Quebec AgreementArticles of Agreement Governing Collaboration Between the Authorities of the U.S.A. and U.K. in the Matter of Tube AlloysMackenzie King, Franklin D. Roosevelt and Winston Churchill at the Quebec Conference in August 1943Signed19 August 1943 (1943-08-19)LocationQuebec City, Quebec, CanadaEffective19 August 1943 (1943-08-19)Expiration7 January 1948 (1948-01-07)Signatories Winston Churchill (UK) F...

Philip II, Margrave of Baden-BadenMargrave Philip II of BadenBorn(1559-02-19)19 February 1559Baden-BadenDied7 June 1588(1588-06-07) (aged 29)Baden-BadenNoble familyHouse of ZähringenFatherPhilibert, Margrave of Baden-BadenMotherMechthild of Bavaria Margrave Philip II of Baden (born 19 February 1559 in Baden-Baden – died 7 June 1588 in Baden-Baden) was from 1571 to 1588 Margrave of the Margraviate of Baden-Baden. He was the son of the Protestant Margrave Philibert of Baden-Baden and th...

 

 

2002 American television film by Charles Beeson This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: Stranded 2002 film – news · newspapers · books · scholar · JSTOR (May 2019) (Learn how and when to remove this template message) StrandedThe Greatest Survivor Story of the YearBased onThe Swiss Family Robinso...

 

 

Strategi Solo vs Squad di Free Fire: Cara Menang Mudah!