什么是存储排列的良好数据结构以及该排列发生的次数

what is a good data structure to store a permutation and how many times that permutation occurs?

本文关键字:排列 数据结构 存储 什么      更新时间:2023-10-16

我的排列是唯一的数字对。我需要浏览一个列表并计算给定排列发生的次数。所以我需要将其记录在数据结构中。

(1,1) 0
(1,2) 5
(1,3) 3
(2,2) 5
(2,3) 2
(3,3) 1

最终,我需要能够按降序对这个容器进行排序,以便我可以获得出现最大次数的排列。多谢!!

使用std::map<std::pair<int, int>, int> .像这样插入:

std::map<std::pair<int, int>, int> myMap;
typedef std::map<std::pair<int, int>, int>::iterator Iterator;
// Insert "permutation" (0,1) with a default of 0 uses
Iterator it=myMap.insert(std::make_pair(std::make_pair(0, 1), 0)).first;
++it->second; // Increment use count - will use old count if already there

您甚至不需要事后对其进行排序,您始终可以在每次插入后记录当前最大值!

请注意,插入物中的外对带有使用次数的默认值。如果元素尚未在映射中,则此值将设置为 0。因此,如果排列已经存在,它将为您找到 map 元素,否则它将插入它并将使用计数设置为零。然后,您只需以任何一种方式递增它!

我只会制作一个对到 int 的无序映射(假设 int 就足够了,您可能需要一个长整数或任意大的整数)。如果键已存在,则只需递增该值,否则将该值设置为 1