随笔- 509  文章- 0  评论- 151  阅读- 22万 

2014-04-24 20:44

题目:对于Facebook、Linkedin这样的社交网站,你要如何设计一个数据结构来表示用户之间的关系呢?比如两个用户互为2nd-degree connection。你要如何设计算法来找出他们之间的联系路径呢?

解法:显然,社交网络的数据是平方级别的,因为任何人的联系往往是C(n, 2) = n * (n - 1) / 2。所以这种数据结构应该是个无向图和有向图的结合。人脉之间是互相建立的,所以是无向图,而“Follow”行为是单向的,所以应该为有向图。如果要发掘两个用户间的人脉路径,广度优先搜索肯定是最简单直白的。单向或是双向广搜可能效率上有一定差别,但对于这样的大型网站肯定都不行,因为响应时间要求很高。如果用空间换取时间,用动态规划的思想,把一度人脉、二度人脉逐层计算并保存下来,这样就能避免重复计算了。算法分为在线和离线两种设计,这样开销巨大的搜索过程,就应该以合理的间隔进行离线计算,保证在线查询的高效响应。如果你问:“我的人脉情况会变化,这样显示出来的结果岂不是错的?”那么我说,下次重新计算的时候,就会对了,你对错误的容忍程度决定了下次服务器重新计算人脉的时间间隔。

代码:

复制代码
 1 // 10.2 Describe how you would design the data structure for people in social network. How would you determine the degree of connections between two people.
 2 // Answer:
 3 // Appartently social network involves a lot of graph thoery. It describes the connections between people.
 4 class Person {
 5     // A lot of data 
 6     vector<Person *> friends;
 7 };
 8 // Basically every people is a node in the grap.
 9 // For two people, if you want to find out through how many people they're connected, BFS may be a practical way.
10 // But it's not effiecient enough, double-end BFS will be a little better.
11 // You may record the list of 2nd degree connections, so you can retrieve 3rd degree connections faster.
12 // And you surely wouldn't be interested in 10th degree connections, as anyone on this earth may be your 10th degree connection.
13 // So it's important to limit the connection search to a small scale of no more than 3rd degree.
14 int main()
15 {
16     return 0;
17 }
复制代码

 

 posted on   zhuli19901106  阅读(182)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示