首页 > 其他 > 详细

Coursera-Algotithms学习

时间:2014-02-19 17:16:07      阅读:381      评论:0      收藏:0      [点我收藏+]

Week1 Job Interview Question

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.

bubuko.com,布布扣
 1 public class SocialNet {
 2     private int N;
 3     private String InputFileName;
 4     public SocialNet(int N,String InputFileName){
 5         this.N = N;
 6         this.InputFileName = InputFileName;
 7     }
 8     public String getTimeString(){
 9         WeightedQuickUnionUF wQUF = new WeightedQuickUnionUF(N);
10         In fin = new In(InputFileName);
11         while(fin.hasNextLine()){
12             String[] lineSplit = fin.readLine().split(" ");
13             wQUF.union(Integer.parseInt(lineSplit[1]), Integer.parseInt(lineSplit[2]));
14             if(wQUF.count() == 1){
15                 return lineSplit[0];
16             }
17         }
18         return "Never";
19     }
20     public static void main(String[] args) {
21         // TODO Auto-generated method stub
22         SocialNet sn = new SocialNet(10,"SocialNetInput.txt");
23         System.out.println(sn.getTimeString());
24     }
25 }
bubuko.com,布布扣

 input File:

bubuko.com,布布扣
20130101 0 2
20130201 0 4
20130301 2 3
20130401 3 4
20130501 4 5
20130601 3 6
20130701 5 6
20130801 2 6
20130901 1 2
20131001 7 3
20131101 0 9
20131201 4 8
20131202 4 3
bubuko.com,布布扣

Coursera-Algotithms学习

原文:http://www.cnblogs.com/jianboqi/p/3555037.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!