Advertisement
jules0707

Social Network Connectivity

Nov 6th, 2017
355
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.15 KB | None | 0 0
  1. import java.util.Arrays;
  2. import edu.princeton.cs.algs4.StdIn;
  3. import edu.princeton.cs.algs4.StdOut;
  4. import edu.princeton.cs.algs4.WeightedQuickUnionPathCompressionUF;
  5.  
  6. /*---------------- TASK -----------------
  7. Social network connectivity. Given a social network containing n members
  8. and a log file containing m timestamps at which times pairs of members formed friendships,
  9. design an algorithm to determine the earliest time at which all members are connected
  10. (i.e., every member is a friend of a friend of a friend ... of a friend).
  11. Assume that the log file is sorted by timestamp and that friendship is an equivalence relation.
  12. The running time of your algorithm should be mlogn or better and use extra space proportional
  13. to n.
  14. */
  15.  
  16. /* SAMPLE DATA
  17.  * 10 //number of components
  18. //timestamps & unions to perform
  19. 100000176 4 3
  20. 100000177 3 8
  21. 100000178 6 5
  22. 100000179 9 4
  23. 100000186 2 1
  24. 100000196 8 9
  25. 100000276 5 0
  26. 100000286 7 2
  27. 100000287 3 6
  28. 100000296 6 1
  29. 100000376 1 0
  30. 100000476 6 7
  31.  */
  32.  
  33. /*Rq : Timestamps are stored in an int[] array type for commodity in solving the task here but obviously  not to do for production!
  34. */
  35.  
  36. // direct implementation of the Union Find algo weighted and with full path compression
  37. // that runs in m log n
  38. public class SocialNetworkConnectivity {
  39.     private static int[] ts;
  40.  
  41.     public SocialNetworkConnectivity() {
  42.         super();
  43.     }
  44.  
  45.     public static void main(String[] args) {
  46.         int n = StdIn.readInt();
  47.         WeightedQuickUnionPathCompressionUF wqupc =
  48.             new WeightedQuickUnionPathCompressionUF(n);
  49.         ts = new int[n]; // we store the timestamps in a seperate array of size proportional to n
  50.         int t = 0;
  51.         int p;
  52.         int q;
  53.         int index = -1;
  54.  
  55.         // as long as every one is not connected we connect more members
  56.         while (wqupc.count() > 1) {
  57.             t = StdIn.readInt();
  58.             Arrays.fill(ts, t);
  59.             p = StdIn.readInt();
  60.             q = StdIn.readInt();
  61.             wqupc.union(p, q);
  62.             index++;
  63.         }
  64.         StdOut.println(
  65.                 " network connected at time: " + Integer.toString(ts[index]));
  66.     }
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement