Coursera Algorithms week1 查并集 练习测验:1 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.
分析:
题目的意思是有一个包含n个成员的社交网络,日志文件log按照时间戳顺序存储了两个成员之间成为朋友的时间,共有m条记录。让我们设计一个算法来根据这个log文件来计算m个成员全部通过朋友关系连通的时间。
这是个典型的并查集。思路是读取日志文件,遍历文件记录,逐条记录union。采用加权quick-union算法,就可以满足mlogn的复杂度要求。作业提交100
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner; import edu.princeton.cs.algs4.StdOut;
import edu.princeton.cs.algs4.WeightedQuickUnionUF; public class SocialNetworkConnUF {
private FileInputStream ins;
private WeightedQuickUnionUF uf;
public SocialNetworkConnUF(int num, FileInputStream ins){
this.ins = ins;
uf = new WeightedQuickUnionUF(num);
} @SuppressWarnings("resource")
public String getEarliestConTime(){
Scanner scanner = new Scanner(ins,"utf-8");
String earliestConTime = null;
while(scanner.hasNextLine()){
String line = scanner.nextLine();
if(line != null && !line.trim().equals("")){
String[] lineArray = line.split(" ");
if(lineArray.length == 3){
String timestamp = lineArray[0];
int p = Integer.parseInt(lineArray[1]);
int q = Integer.parseInt(lineArray[2]);
if(uf.connected(p, q)) continue;
uf.union(p,q);
if(uf.count() == 1) {
earliestConTime = timestamp;
break;
}
}
} }
return earliestConTime;
}
public static void main(String[] args){
FileInputStream ins;
try {
ins = new FileInputStream("socialNetworkLog.txt");
SocialNetworkConnUF socialNet = new SocialNetworkConnUF(10, ins);
String earliestConnTime = socialNet.getEarliestConTime();
StdOut.println(" the earliest connected time is :" + earliestConnTime);
} catch (FileNotFoundException e) {
e.printStackTrace();
} }
/*
* socialNetworkLog.txt
* 20170714001 0 1
* 20170714002 4 5
* 20170714003 8 9
* 20170714004 2 4
* 20170714005 5 6
* 20170714006 7 8
* 20170714007 2 5
* 20170714008 6 7
* 20170714009 1 2
* 20170714010 0 3
* 20170714011 1 9
* 20170714012 3 7
*
*/
}
Coursera Algorithms week1 查并集 练习测验:1 Social network connectivity的更多相关文章
- Coursera Algorithms week1 查并集 练习测验:3 Successor with delete
题目原文: Given a set of n integers S = {0,1,…,N-1}and a sequence of requests of the following form: Rem ...
- Coursera Algorithms week1 查并集 练习测验:2 Union-find with specific canonical element
题目原文: Add a method find() to the union-find data type so that find(i) returns the largest element in ...
- Coursera Algorithms week1 算法分析 练习测验: Egg drop 扔鸡蛋问题
题目原文: Suppose that you have an n-story building (with floors 1 through n) and plenty of eggs. An egg ...
- Coursera Algorithms week1 算法分析 练习测验: 3Sum in quadratic time
题目要求: Design an algorithm for the 3-SUM problem that takes time proportional to n2 in the worst case ...
- Coursera Algorithms week2 基础排序 练习测验: Dutch national flag 荷兰国旗问题算法
第二周课程的Elementray Sorts部分练习测验Interview Questions的第3题荷兰国旗问题很有意思.题目的原文描述如下: Dutch national flag. Given ...
- Coursera Algorithms week2 基础排序 练习测验: Permutation
题目原文: Given two integer arrays of size n , design a subquadratic algorithm to determine whether one ...
- Coursera Algorithms week2 基础排序 练习测验: Intersection of two sets
题目原文: Given two arrays a[] and b[], each containing n distinct 2D points in the plane, design a subq ...
- Coursera Algorithms week4 基础标签表 练习测验:Inorder traversal with constant extra space
题目原文: Design an algorithm to perform an inorder traversal of a binary search tree using only a const ...
- Coursera Algorithms week4 基础标签表 练习测验:Check if a binary tree is a BST
题目原文: Given a binary tree where each
随机推荐
- Python语言之函数
1.函数的定义与调用 def function(x): print("function(%s)"%x) function("hello") #call the ...
- Lazarus Reading XML- with TXMLDocument and TDOMNode
这里读取'HistoryPath' ,'TracePath' 元素下的‘value’属性使用的是 var xmlCfg: TXMLDocument; .... function ReadXMLCFG: ...
- 浏览器的 local storage
浏览器 local storage 本地存储 session storage 会话存储 cookies 本地存储 1. local stora ...
- centos7 安装 PostgreSql
确定你是管理员,然后运行命令: yum -y install postgresql-server postgresql-contrib 初始化数据库 postgresql-setup initdb 启 ...
- CPU 指令集(Instruction Set Architecture, ISA)
本文摘自网络 概念 指令集是存储在CPU内部,对CPU运算进行指导和优化的硬程序,用来引导CPU进行加减运算和控制计算机操作系统的一系列指令集合.拥有这些指令集,CPU就可以更高效地运行.系统所下达的 ...
- css3 animation 中的 steps
steps Specifies a stepping function, described above, taking two parameters. The first parameter spe ...
- Django REST framework 初识
一.官网快速实例 quickstart # 安装 RESTful pip install djangorestframework 二.序列化 models.py from django.db impo ...
- 小白两篇博客熟练操作MySQL 之 第一篇
小白两篇博客熟悉操作MySQL 之 第一篇 一.概述 1. 什么是数据库? 答: 储存数据的仓库, 如: 在ATM的事例中创建的一个db 目录, 称为数据库 2. 什么是Mysql, Oracl ...
- IDEA 工具使用报错总结
读前语:此文章仅给非入门级观看 1.使用Debug 无法运行,而使用Run 则正常启动,报错代码如下 1 Error running 'jx_web': Unable to open debugge ...
- TOC 1. TODO springboot优雅关机
TODO start and stop as a linux service web container(tomcat ,undertow) gracefully shutdown gracefull ...