Ejemplo n.º 1
0
    def findRedundantDirectedConnection(self, edges):
        """
        :type edges: List[List[int]]
        :rtype: List[int]
        """
        uf = UF(len(edges))
        self.adjList = [[] for i in range(len(edges)+1)]
        hasFather = [False] * (len(edges)+1)     # Whether a vertex has already got a parent
        criticalEdge = None

        res = None
        for e in edges:
            n1, n2 = e[0], e[1]
            self.adjList[n1].append(n2)
            if hasFather[n2]:
                criticalEdge = (e[0], e[1])   
            hasFather[n2] = True       
            if uf.connected(n1, n2):
                
                cycleEdge = (e[0], e[1])
            else:
                uf.union(n1, n2)
        if not criticalEdge:                                    # Case 1
            return cycleEdge
        self.visited = [False] * (len(edges)+1)
        (w, v) = self.detectCycle(criticalEdge[1])
        return (w, v) if w else criticalEdge       
Ejemplo n.º 2
0
    def accountsMergeUF(self, accounts):
        """
        :type accounts: List[List[str]]
        :rtype: List[List[str]]
        """

        # union find
        d = {}  # key:val = email:index
        uf = UF(len(accounts))
        for i, a in enumerate(accounts):
            for email in a[1:]:
                if email in d:
                    uf.union(i, d[email])
                else:
                    d[email] = i

        # merge accounts
        from collections import defaultdict
        res0 = defaultdict(set)  # key:val = index: {set of emails}
        for i in range(len(accounts)):
            res0[uf.find(i)] |= set(accounts[i][1:])
        # convert into required format
        res = []
        for k, v in res0.items():
            res.append([accounts[k][0]] + sorted(v))

        return res
Ejemplo n.º 3
0
def Kruskal (G, w):
	T = []; cout = 0;
	A = G.A # l'ensemble des arretes de G
	S = sorted(A) # A trie selon w croissant
	for (u, v) in S:
		if not UF.find(u, v): # si (u, v) ne forme pas de cycle
			T.append((u, v))
			cout += w[(u, v)]
			UF.union(u, v)
	return (T, cout)
Ejemplo n.º 4
0
    def findCircleNum(self, M):
        """
        :type M: List[List[int]]
        :rtype: int
        """
        n = len(M[0])

        uf = UF(n)
        for i in range(n):
            for j in range(n):
                if i != j and M[i][j] == 1:
                    uf.union(i, j)
        return uf.count()
Ejemplo n.º 5
0
 def __init__(self, g: EdgeWeightedGraph) -> None:
     self.mst = []
     self.pq = PriorityQueue()
     for e in g.edges():
         self.pq.put(e)
     uf = UF(g.V)
     while not self.pq.empty() and len(self.mst) < g.V - 1:
         e = self.pq.get()
         v = e.v
         w = e.w
         if uf.connected(v, w):
             continue
         uf.union(v, w)
         self.mst.append(e)
Ejemplo n.º 6
0
 def findRedundantConnection(self, edges):
     """
     :type edges: List[List[int]]
     :rtype: List[int]
     """
     uf = UF(len(edges))
     res = None
     for e in edges:
         n1, n2 = e[0], e[1]
         if uf.connected(n1, n2):
             res = e[:]
         else:
             uf.union(n1, n2)
     return res
Ejemplo n.º 7
0
    def __init__(self, g):
        self.mst = Queue()
        self.pq = MinPQ()
        self.uf = UF(g.v)

        for e in g.edges:
            self.pq.insert(e)

        while not self.pq.is_empty() and self.mst.size() < g.v - 1:
            e = self.pq.del_min()
            v = e.either()
            w = e.other(v)
            if self.uf.connected(v, w):
                continue
            self.mst.enqueue(e)
            self.uf.union(v, w)
Ejemplo n.º 8
0
 def Kruskal(self):
     C = UF(self.getn())
     MST = []
     edges = sorted(self.getEdges(), key=lambda tup: tup[2])
     for i in range(len(edges)):
         if C.find(edges[i][0]) != C.find(edges[i][1]):
             C.union(C.find(edges[i][0]), C.find(edges[i][1]))
             MST.append(edges[i])
     for i in range(len(MST)):
         if i == 0: print "[" + str(MST[i]) + ","
         elif i == len(MST) - 1: print " " + str(MST[i]) + "]"
         else: print " " + str(MST[i]) + ","
Ejemplo n.º 9
0
    def Boruvka(self):
        # to build the MST, results represented by _mst
        self._mst.clear()
        # load UF  class for union and find
        from UF import UF
        
        uf = UF(self._nNodes)

        # let's start the algorithm
        
        # store the cheapest edge of subset
        cheapest = [-1]*self._nNodes

        # union components until there are only one component

        while uf.numTrees() > 1:
            
            # update cheapest edges

            for i in range(self._nEdges):

                # find components of two ends of an edge
                src, dest, w = self._edges[i][0:3]
                w = w['weight']
                srcTree = uf.find(src)
                destTree = uf.find(dest)

                # if they are not unioned by now, update the cheapest edge

                if srcTree != destTree:
                    if cheapest[srcTree] == -1 or cheapest[srcTree][2] > w :
                        cheapest[srcTree] = [src, dest, w]
                    
                    if cheapest[destTree] == -1 or cheapest[destTree][2] > w :
                        cheapest[destTree] = [src, dest, w]

            # add the cheapest edges to current MST
            for node in range(self._nNodes):

                # find two disjointed trees and union them
                if cheapest[node] != -1:
                    # after above step, only cheapest[treeRoot] is not equal to -1, and they contain the cheapest edge for tree root
                    src, dest, w = cheapest[node]
                    uf.union(src, dest)
                    self._mst.addEdge(src, dest, w)
                    # srcTree = uf.find(src)
                    # destTree = uf.find(dest)

                    # if srcTree != destTree:
                    #     uf.union(srcTree, destTree)
                    #     # build the _mst
                    #     _mst.addEdge(src, dest, w)


            # reset the cheapest edges for next level union
            cheapest = [-1] * self._nNodes

        return self._mst
    def __init__(self, G):
        self._G = G
        self._mst = []

        cc = CC(G)
        print(cc.ccount)
        if (cc.ccount > 1):
            return
        edges = []
        for v in range(G.V):
            for w in G.adj(v):
                if v < w:
                    edges.append(WeightedEdge(v, w, G.get_weight(v, w)))

        edges = sorted(edges, key=lambda key: key.weight)
        uf = UF(self._G.V)
        for edge in edges:
            v = edge.v
            w = edge.w
            if uf.isConnected(v, w):
                continue
            else:
                uf.union(v, w)
                self._mst.append(edge)
Ejemplo n.º 11
0
import math
from Edge import Edge
from time import clock
from UF import UF

f = open('clustering1.txt')

n = int(f.readline())

adj = [[] for i in range(n + 1)]
uf = UF(n + 1)
edge_lst = []

for line in f:
    u, v, cost = [int(val) for val in line.split()]
    e = Edge(u, v, cost)
    edge_lst.append(e)

start = clock()
edge_lst.sort(key=lambda e: e.weight)
# for e in edge_lst:
# print(e)

MST_edges = []
total_cost = 0
num_clusters = 4

i = 0
while uf.count > 1 + num_clusters:
    # print("Edge: " + str(i))
    e = edge_lst[i]
Ejemplo n.º 12
0
from levels import levels
from UF import UF
moves, grid = levels[8]


def get_cell(row, col):
    return row * 10 + col


uf = UF()
for row in xrange(16):
    for col in xrange(10):
        cell_id = get_cell(row, col)
        cell = grid[row][col]

        if row != 15:  # Horizontal unioning
            if cell == grid[row][col + 1]:
                uf.union(cell_id, get_cell(row, col + 1))

        if col != 9:  # Vertical unioning
            if cell == get[row + 1][col]:
                uf.union(cell_id, get_cell(row + 1, col))
Ejemplo n.º 13
0
from levels import levels
from UF import UF
moves,grid = levels[8]

def get_cell(row, col):
    return row * 10 + col

uf = UF()
for row in xrange(16):
    for col in xrange(10):
        cell_id = get_cell(row, col)
        cell = grid[row][col]

        if row != 15: # Horizontal unioning
            if cell == grid[row][col+1]:
                uf.union(cell_id, get_cell(row, col+1))

        if col != 9: # Vertical unioning
            if cell == get[row+1][col]:
                uf.union(cell_id, get_cell(row+1, col))



Ejemplo n.º 14
0
#     if n != len(s2):
#         raise ValueError
#     for i in range(n):
#         if s1[i] == s2[i]:
#             count += 1
#     return count

# print(hamming_dist('0101', '1100'))

f = open('clustering_big.txt')

s = f.readline().split()
n = int(s[0])
nbits = int(s[1])

uf = UF(n)
d = {}  # hash table

# initialize
for i in range(n):
    line = f.readline()
    s = ''.join(line.split())
    if s in d:
        uf.union(d[s], i)  # merge same verts
    else:
        d[s] = i

# merge pair of points with distance 1
for s, j in d.items():
    for k in range(nbits):
        # flip kth bits