/**
  * Find k clusters in given graph. Returns maximum spacing between clusters.
  *
  * @param k - number of cluster to find
  * @return spacing between clusters
  */
 public int findClusters(final int k) {
   Preconditions.checkArgument(k >= 2);
   final Edge[] edges = g.getEdges();
   Arrays.sort(edges);
   final UF uf = new UF(g.getVertexCount());
   for (Edge edge : edges) {
     if (uf.connected(edge.from, edge.to)) continue;
     if (uf.count() > k) uf.union(edge.from, edge.to);
     else return edge.weight;
   }
   throw new IllegalStateException("Failed to reach " + k + " clusters. This should not happen.");
 }
예제 #2
0
파일: ErdosRenyi.java 프로젝트: enali/algs4
  public static int count(int N) {
    int edges = 0;
    UF uf = new UF(N);
    while (uf.count() > 1) {
      int i = StdRandom.uniform(N);
      int j = StdRandom.uniform(N);
      if (j == i) j = StdRandom.uniform(N);

      // if (uf.connected(i,j)) continue;

      uf.union(i, j);
      edges++;
    }
    return edges;
  }
예제 #3
0
  public static void main(String[] args) {
    int N = StdIn.readInt();
    UF uf = new UF(N);

    // read in a sequence of pairs of integers (each in the range 0 to N-1),
    // calling find() for each pair: If the members of the pair are not already
    // call union() and print the pair.
    while (!StdIn.isEmpty()) {
      int p = StdIn.readInt();
      int q = StdIn.readInt();
      if (uf.connected(p, q)) continue;
      uf.union(p, q);
      StdOut.println(p + " " + q);
    }
    StdOut.println("# components: " + uf.count());
  }