c++ - 在我的 friend 圈中找到最受欢迎的点赞

标签 c++ algorithm stl popularity top-n

我正在研究一种在我的 friend 网络中找到最受欢迎的点赞的方法。 “在我的 friend 圈中最受欢迎”的定义是“我的 friend 点赞数最多”。

假设每个 friend 都有一个唯一的id,并且有一些喜欢的页面。因此,给定一组这样的 friend ,我想找到最多 friend 喜欢的人,以及还有喜欢这个东西的 friend 。本质上,我想展示类似“您的 friend X、Y 和 Z 喜欢这个”的内容。

我的第一个解决方案是使用 Map(用于存储反向映射:like->set)和 Priority Queue(用于查找前 N 个)。这是我的算法(使用 C++ STL):

map< like, set<friend> > like2friendsMap;
for each friend {
  for each like {
    like2friendsMap[like].insert(friend); //populate the map
  }
}

priority_queue< pair<like, int> > pq;
for each like in like2friendsMap {
  int count = like2friendsMap[like].size(); //no. of friends who like this or "popularity"
  pq.push(like, count); //count is the priority
}

map< like, set<friend> > result
for i in 1 to N { //N is how many popular items I want
   result = pq.top();  //gives me the element with highest priority (most popular like)
   pq.pop();
}

由于 STL 在内部使用红黑树来实现映射,并使用最小/最大堆来实现优先级队列,所以这种方法对我来说似乎非常快。但是如果我有 100 个 friend 并且每个 friend 都有 100 个赞,那么内存使用量将是巨大的。当然,不是存储整个对象,我应该使用 friend id 和 like id 进行所有计算,这将大大减少内存使用量。

还有哪些算法或数据结构可以用来提高效率(提高速度,减少内存)?出于某种原因,我无法针对每个点赞存​​储 friend 列表,它必须在运行时计算。我正在使用 C++ 开发它,因此使用 STL 或 boost 的解决方案会更好。

最佳答案

create an integer list allPages which can be referenced by page
initialize it with 0
for every friend f
{
    for every page p liked by f
    {
        allPages[p]++;
    }
}
get the maximum of the allPages[p]

如果P是页数,那么它的空间复杂度就是O(P)

如果F 是 friend 的数量,L 是每个人喜欢的平均页面。那么它的时间复杂度就是O(F*L)。因此,即使您再次遍历所有 friend 以检查谁都喜欢该页面,也不会增加太多复杂性。

O(F*L) + O(F) would remain O(F*L)

我认为最好再次迭代而不是存储 friend 。

或者您可以存储页面的反向引用本身。也就是说,对于每个页面,存储喜欢的 friend 列表。这不会占用太多空间,而且会以最小的复杂性完成您的工作。

关于c++ - 在我的 friend 圈中找到最受欢迎的点赞,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12456515/

相关文章:

c++ - OpenGL glfw无法使用着色器绘制点

arrays - 给定一个数字数组,形成一个子集,使其可以表示(允许添加数字)给定数组中的任何数字

algorithm - Dijkstra算法如何找到最短路径?

STL - 如何在 Ada 中进行 std::rotate?

c++ - cv::connectedComponents 与 cv::findContours 的实现和速度差异

c++ - 使用类模板需要模板参数列表链接列表

c++ - 安装时如何使NodeJS软件包生成C++/WebAssembly?

c# - 约束加权选择

c++ - STL:指针关联排序容器:排序谓词模板

c++ - 用于清除指针 vector 的模板函数