All rights reserved. All rights reserved.
Welcome reprint, please indicate the source when reproduced:
http://blog.csdn.net/xiaofei_it/article/details/51524671
To prevent rigid thinking, brush an algorithmic question every day. It has been brushed for a few days now, send point code.
I have built an open source project, and every day the topic is in it:
Https://github.com/Xiaofei-it/Algorithms
Most of the algorithms are written by myself, without reference to the online generic code. The reader may find the code obscure because it is my own understanding.
The last few days have been writing something original, mostly non-recursive. In the future, ready to brush points DP, greedy and other problems.
The following are supported for any type of check set:
/p>
/** * * Xiaofei * * Licensed under the Apache License, Version 2.0 (the "License"); * You are not a use this file except in compliance with the License. * Obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * unless required by applicable Law or agreed into writing, software * Distributed under the License is distributed on a "as is" BASIS, * without Warra Nties or CONDITIONS of any KIND, either express OR implied. * See the License for the specific language governing permissions and * limitations under the License. * */package xiaofei.algorithm;import java.util.hashmap;/** * Created by Xiaofei on 16/5/22. */public class Disjointset<t> {private hashmap<t, node<t>> map = new hashmap<> (); Public Disjointset () {} public void MakeSet (T data) {if (Map.containskey (data)) {return; } map.put (data, new node<t> (data)); } private node<t> Findinternal (node< T> node) {if (Node.parent! = node) {node.parent = Findinternal (node.parent); } return node.parent; Public t find (t data) {node<t> Node = map.get (data); if (node = = null) {return null; } return findinternal (node). data; } public void Union (t data1, T data2) {node<t> Node1 = Map.get (data1), Node2 = Map.get (data2); if (Node1 = = NULL | | node2 = = NULL) {return; } Node1 = Findinternal (Node1); Node2 = Findinternal (Node2); if (Node1.rank < Node2.rank) {node1.parent = Node2; } else if (Node1.rank > Node2.rank) {node2.parent = Node1; } else {node1.parent = Node2; ++node2.rank; }} private static class Node<t> {T data; Node<t> parent; Rank is not depth!!! int rank; Node (T data) {this.data = data; This.parent = this; This.rank = 0; } }}
Every day to brush algorithm problem 20160522: Support various types of and check set