Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Map<String, String> people;
- Map<String, Integer> rank;
- public DisjointSubsets() {
- people = new HashMap<>();
- rank = new HashMap<>();
- }
- public String find(String element) throws IllegalArgumentException {
- // TODO
- // should throw IllegalArgumentException if the element is not present
- if (element == null || element.equals("") || !people.containsKey(element)) {
- throw new IllegalArgumentException();
- }
- String firstParent = people.get(element);
- while (!people.get(firstParent).equals(firstParent)) {
- firstParent = people.get(firstParent);
- }
- return firstParent;
- }
- // should throw IllegalArgumentException if any of elements is not present
- public void union(String element1, String element2) throws IllegalArgumentException {
- // TODO
- // should throw IllegalArgumentException if any of elements is not present
- if (element1 == null || element2 == null || element2.equals("") || element1.equals("") || !people.containsKey(element2) || !people.containsKey(element1)) {
- throw new IllegalArgumentException();
- }
- String x = find(element1);
- String y = find(element2);
- if (find(element1).equals(element2)) {
- return;
- }
- if (rank.get(x) > rank.get(y))
- people.put(y, x);
- else if (rank.get(x) < rank.get(y))
- people.put(x, y);
- else {
- people.put(x, y);
- rank.put(y, rank.get(y) + 1);
- }
- }
- public void addSubset(String element) throws IllegalArgumentException {
- // TODO
- // should throw IllegalArgumentException if the element is already present
- if (element == null || element.equals("") || people.containsKey(element)) {
- throw new IllegalArgumentException();
- }
- people.put(element, element);
- rank.put(element, 0);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement