• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* Copyright 2018 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_TF2TENSORRT_SEGMENT_UNION_FIND_H_
17 #define TENSORFLOW_COMPILER_TF2TENSORRT_SEGMENT_UNION_FIND_H_
18 
19 namespace tensorflow {
20 namespace tensorrt {
21 namespace segment {
22 
23 // Union-Find data structure.
24 // Each cluster has an associated value; when merging clusters we can control
25 // which value becomes the representative of the merged clusters. Values must be
26 // copyable.
27 template <typename T>
28 class UnionFind {
29  public:
UnionFind()30   UnionFind() : size_(1), parent_(nullptr) {}
UnionFind(const T & v)31   explicit UnionFind(const T& v) : size_(1), parent_(nullptr), value_(v) {}
32 
33   // Returns the number of elements in a cluster.
Size()34   int Size() { return FindRoot()->size_; }
35 
36   // Merges this cluster with 'other'. This cluster's value becomes
37   // the value of the merged cluster; the value of 'other' is ignored.
38   void Merge(UnionFind* other);
39 
40   // Each cluster has an associated value. Retrieves the value associated
41   // with this cluster.
ParentValue()42   T& ParentValue() { return FindRoot()->value_; }
43 
44   // Get the original value of this node.
Value()45   T& Value() { return value_; }
46 
47  private:
48   // Finds the root element of the cluster. Performs path compression.
49   UnionFind* FindRoot();
50 
51   int size_;
52   UnionFind* parent_;
53   T value_;
54 };
55 
56 template <typename T>
Merge(UnionFind * other)57 void UnionFind<T>::Merge(UnionFind* other) {
58   UnionFind<T>* a = FindRoot();
59   UnionFind<T>* b = other->FindRoot();
60   if (a == b) return;
61 
62   b->parent_ = a;
63   a->size_ += b->size_;
64 }
65 
66 template <typename T>
FindRoot()67 UnionFind<T>* UnionFind<T>::FindRoot() {
68   if (!parent_) return this;
69   // Path compression: update intermediate nodes to point to the root of the
70   // equivalence class.
71   parent_ = parent_->FindRoot();
72   return parent_;
73 }
74 
75 }  // namespace segment
76 }  // namespace tensorrt
77 }  // namespace tensorflow
78 
79 #endif  // TENSORFLOW_COMPILER_TF2TENSORRT_SEGMENT_UNION_FIND_H_
80