course并查集的课后题之一,看完之后没有开始没有什么思路,也没找到什么答案,想了想写了一下,感觉受益挺多的
问题描述:
Social network connectivity. Given a social network containing n members and a log file containing m timestamps at which times pairs of members formed friendships, design an algorithm to determine the earliest time at which all members are connected (i.e., every member is a friend of a friend of a friend … of a friend). Assume that the log file is sorted by timestamp and that friendship is an equivalence relation. The running time of your algorithm should be mlogn or better and use extra space proportional to n.
解题思路:
首先对于这样的问题我们肯定要使用并查集来求解,题目求是在散列刚刚全部连通的时候的状态,所以我们需要判断什么时候刚刚连通。这时候会想到,全部连通时只会有一个父节点的存在所以,当我们做一次连接操作的时候做一次父节点的判断就行了,当使用weight quick union 的查询父节点操作的时间复杂度为logn,总的复杂度m(logn+1)=mlogn所以可解,下面附上java实现代码,希望可以帮助和我一样的初学者。