'''Translation of the following code from C++ to Pythonstruct UnionFind { std::vector<u64> parent, ranks; explicit UnionFind(u64 size) { pa ...

#8
by EvgeniyZh - opened
BigCode org

Question:

'''
Translation of the following code from C++ to Python
struct UnionFind {
std::vector parent, ranks;

explicit UnionFind(u64 size) {
parent = std::vector(size);
ranks = std::vector(size);
for (u64 i = 0; i < size; ++i) {
parent[i] = i;
ranks[i] = 1;
}
}

u64 find(u64 x) {
if (x != parent[x]) return parent[x] = find(parent[x]);
return x;
}

void link(u64 x, u64 y) {
x = find(x);
y = find(y);
if (x == y) return;
if (ranks[x] >= ranks[y]) {
parent[y] = x;
if (ranks[x] == ranks[y]) ++ranks[x];
} else {
parent[x] = y;
}
}
};
'''
class UnionFind:

Answer:

'''
Translation of the following code from C++ to Python
struct UnionFind {
  std::vector parent, ranks;


  explicit UnionFind(u64 size) {
    parent = std::vector(size);
    ranks = std::vector(size);
    for (u64 i = 0; i < size; ++i) {
      parent[i] = i;
      ranks[i] = 1;
    }
  }


  u64 find(u64 x) {
    if (x != parent[x]) return parent[x] = find(parent[x]);
    return x;
  }


  void link(u64 x, u64 y) {
    x = find(x);
    y = find(y);
    if (x == y) return;
    if (ranks[x] >= ranks[y]) {
      parent[y] = x;
      if (ranks[x] == ranks[y]) ++ranks[x];
    } else {
      parent[x] = y;
    }
  }
};
'''
class UnionFind:


    def __init__(self, size):
        self.parent = [i for i in range(size)]
        self.ranks = [1]*size




    def find(self, x):
        if self.parent[x]!= x:
            self.parent[x] = self.find(self.parent[x])
        return self.parent[x]




    def link(self, x, y):
        x = self.find(x)
        y = self.find(y)


        if x == y:
            return


        if self.ranks[x] > self.ranks[y]:
            self.parent[y] = x
        elif self.ranks[x] < self.ranks[y]:
            self.parent[x] = y
        else:
            self.parent[y] = x
            self.ranks[x] += 1


<|endoftext|>

Sign up or log in to comment