22.1.22 并查集和KMP算法
1.并查集结构
1)实现:
-
并查集有多种实现方式,例如向上指的图的方式,数组的方式等等。其根本思想就在于准确记录某个节点的根节点,这个这种记录就能够很快的实现并查集的两种主要的功能:合并和查询。
2)两种优化方法:
-
压缩路径;
-
在合并时将深度小的树合并到深度大的树。
3)code:
public static class PointUnion<V>
{
private V value;
public PointUnion(V value)
{
this.value = value;
}
}
public static class UnionSet<V>
{
public HashMap<V,PointUnion<V>> PUmap ;
public HashMap<PointUnion<V>,PointUnion<V>> Fathermap ;
public HashMap<PointUnion<V>,Integer> Rankmap ;
public UnionSet(List<V> list)
{
PUmap = new HashMap<V,PointUnion<V>>();
Fathermap = new HashMap<PointUnion<V>,PointUnion<V>>();
Rankmap = new HashMap<PointUnion<V>,Integer>();
for(V value : list)
{
PointUnion<V> PU = new PointUnion<V>(value);
PUmap.put(value, PU);
Fathermap.put(PU, PU);
Rankmap.put(PU, 1);
}
}
public PointUnion<V> FindFather(PointUnion<V> PU)
{