1 /* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
2 
3 Licensed under the Apache License, Version 2.0 (the "License");
4 you may not use this file except in compliance with the License.
5 You may obtain a copy of the License at
6 
7     http://www.apache.org/licenses/LICENSE-2.0
8 
9 Unless required by applicable law or agreed to in writing, software
10 distributed under the License is distributed on an "AS IS" BASIS,
11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 See the License for the specific language governing permissions and
13 limitations under the License.
14 ==============================================================================*/
15 
16 #ifndef TENSORFLOW_COMPILER_JIT_UNION_FIND_H_
17 #define TENSORFLOW_COMPILER_JIT_UNION_FIND_H_
18 
19 namespace tensorflow {
20 
21 // Union-Find data structure.
22 // Each cluster has an associated value; when merging clusters we can control
23 // which value becomes the representative of the merged clusters. Values must be
24 // copyable.
25 template <typename T>
26 class UnionFind {
27  public:
UnionFind()28   UnionFind() : rank_(0), size_(1), parent_(nullptr) {}
29 
30   // Returns the number of elements in a cluster.
Size()31   int Size() { return FindRoot()->size_; }
32 
33   // Merges this cluster with 'other'. This cluster's value becomes
34   // the value of the merged cluster; the value of 'other' is ignored.
35   void Merge(UnionFind* other);
36 
37   // Each cluster has an associated value. Retrieves the value associated
38   // with this cluster.
Get()39   T& Get() { return FindRoot()->value_; }
40 
41  private:
42   // Finds the root element of the cluster. Performs path compression.
43   UnionFind* FindRoot();
44 
45   int rank_;
46   int size_;  // Size of the cluster.
47   UnionFind* parent_;
48   T value_;
49 };
50 
51 template <typename T>
Merge(UnionFind * other)52 void UnionFind<T>::Merge(UnionFind* other) {
53   UnionFind<T>* a = FindRoot();
54   UnionFind<T>* b = other->FindRoot();
55   if (a == b) return;
56   if (a->rank_ > b->rank_) {
57     b->parent_ = a;
58     a->size_ += b->size_;
59     return;
60   }
61 
62   a->parent_ = b;
63   if (a->rank_ == b->rank_) {
64     b->rank_++;
65   }
66   b->value_ = a->value_;
67   b->size_ += a->size_;
68 }
69 
70 template <typename T>
FindRoot()71 UnionFind<T>* UnionFind<T>::FindRoot() {
72   if (!parent_) return this;
73   // Path compression: update intermediate nodes to point to the root of the
74   // equivalence class.
75   parent_ = parent_->FindRoot();
76   return parent_;
77 }
78 
79 }  // namespace tensorflow
80 
81 #endif  // TENSORFLOW_COMPILER_JIT_UNION_FIND_H_
82