import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;
public class E1_5_17 {
public static void main(String[]args){
int N= StdIn.readInt();
int cnt=RandomConnection.count(N);
StdOut.printf("N=%8d count=%15d\n",N,cnt);
}
}
import edu.princeton.cs.algs4.StdRandom;
public class RandomConnection {
public static int count(int N){
//Union find.随机产生pair,直到所有点连在一起,返回产生的数的个数
WeightedQuickUnionUF uf=new WeightedQuickUnionUF(N);
int cnt=0;
while (uf.count()!=1){
int p= StdRandom.uniform(0,N);
int q=StdRandom.uniform(0,N);
uf.union(p,q);//函数中会判断是否已经连接
cnt+=2;
}
return cnt;
}
}
import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;
public class WeightedQuickUnionUF {
public static void main(String[]args){
//Solve dynamic connectivity problem on StdIn.
int N= StdIn.readInt();
WeightedQuickUnionUF uf=new WeightedQuickUnionUF(N);
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(uf.count()+" components");
}
private int[]id; //parent link(site indexed)
private int[]sz; //size of component for roots(site indexed) 只有根节点存储的是树的大小
private int count;//number of component
public WeightedQuickUnionUF(int N){
count=N;
id=new int[N];
for (int i=0;i<N;i++) id[i]=i;
sz=new int[N];
for (int i=0;i<N;i++) sz[i]=1;
}
public int count(){
return count;
}
public boolean connected(int p,int q){
return find(p)==find(q);
}
public int find(int p){
//Follow links to find a root.
while (p!=id[p])p=id[p];
return p;
}
public void union(int p,int q){
int i=find(p);
int j=find(q);
if (i==q)return;
//Make smaller root point to large one.
if (sz[i]<sz[j]){id[i]=j;sz[j]+=sz[i];}
else {id[j]=i;sz[i]+=sz[j];}
count--;
}
}