zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    异常处理 Exception
    C#使用SQLite出错:无法加载 DLL“SQLite.Interop.dll”,找不到指定的模块
    NullableKey:解决Dictionary中键不能为null的问题 zt
    STSdb
    C# 如何获取某个类型或类型实例对象的大小
    CORREL
    C# 深复制
    mysql数据库创建函数过程
    mysql 数据库怎样快速的复制表以及表中的数据
    代码优化(一)
  • 原文地址:https://www.cnblogs.com/jianboqi/p/3555037.html
Copyright © 2011-2022 走看看