1.5.4在正文的加权quick-union算法示例中,对于输入的每一对整数(包括对照输入和最坏情况下的输入),给出id[]和sz[]数组的内容以及访问数组的次数。
答:
1)示例:
2)对照输入:
3)最坏输入
4)code:
public class WeightedQuickUnionUF
{
private int[] id;
private int[] sz;
private int count;
public WeightedQuickUnionUF(int N)
{
count=N;
id=new int[N];
for (int i=0;i<N;i++)
{
id[i]=i;
StdOut.printf("%3d",i);
}
StdOut.println();
//
sz=new int[N];
for (int i=0;i<N;i++)
sz[i]=1;
//
}
public int count()
{return count;}
boolean connected(int p,int q)
{return find(p)==find(q);}
public int find(int p)
{
while(p!=id[p]) p=id[p];
return p;
}
public void union(int p,int q)
{
int i=find(p);
int j=find(q);
StdOut.printf(" i=%d j=%d
",i,j);
if(i==j) return;
if(sz[i]<sz[j])
{
id[i]=j;
sz[j]=sz[j]+sz[i];
}
else
{
id[j]=i;
sz[i]=sz[i]+sz[j];
}
count--;
//
for (int k=0;k<id.length;k++)
StdOut.printf("%3d",id[k]);
StdOut.printf("
");
for (int k=0;k<id.length;k++)
StdOut.printf("%3d",sz[k]);
StdOut.printf("
");
}
public static void main(String[] qrgs)
{
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;
StdOut.printf("p=%d q=%d",p,q);
uf.union(p,q);
}//end while
}//end main
}//end class