Coursera-Algotithms学习

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.

 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 }

 input File:

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

 

你可能感兴趣的:(Go)