您的位置:首页 > 产品设计 > UI/UE

Week1-3Quick Union

2015-09-09 22:32 309 查看

Data Structure

Integer array id[] of size N

Root of i isid[id[id[…id[i]…]]](keep going until it doesn’t change)

Operations

Find( p, q ): check if p and q have the same root

Union( p, q ): to merge components containing p and q, set id of p’s root to the id of q’s root

Implementation

public class QuickUnionUF
{
private int[] id;

public QuickUnionUF( int N )
{
id = new int
;
for( int i = 0; i< N; i++ )
{
id[i] = i;
}
}

private int root( int i )
{
// chase parent pointer until reach root
while( i != id[i] )
{
i = id[i];
}
return i;
}

public boolean connected( int p, int q )
{
return root( p ) == root( q );
}

public void union( int p, int q )
{
int i = root( p ),
j = root( q );
id[i] = j;
}
}


Cost Model

<
4000
td align="center">O(N)
AlgorightmInitializeUnionFind
quick-findO(N)O(N)O(1)
quick-unionO(N)O(N)

Defects

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: