示例#1
0
文件: main.py 项目: ykmc/contest
def main():
    N, M, L = map(int, input().split())
    ABC = [tuple(map(int, input().split())) for _ in range(M)]
    Q = int(input())
    ST = [tuple(map(int, input().split())) for _ in range(Q)]

    # 町の最短距離を求める
    A = np.array([[inf] * N] * N)
    for a, b, c in ABC:
        A[a - 1][b - 1] = c
        A[b - 1][a - 1] = c
    A = csg.floyd_warshall(A)

    # 求めた町の距離が L以下 に 1の辺をはる (給油なしでたどり着ける)
    B = np.array([[inf] * N] * N)
    for i in range(N):
        for j in range(N):
            if A[i][j] <= L:
                B[i][j] = 1
    # 最短距離を求める
    B = csg.floyd_warshall(B)

    for s, t in ST:
        if B[s - 1][t - 1] == inf:
            print(-1)
        else:
            print(int(B[s - 1][t - 1] - 1))
示例#2
0
文件: E.py 项目: k-harada/AtCoder
def main():
    n, m, le = map(int, input().split())
    g1 = (le + 1) * np.zeros((n, n))
    for _ in range(m):
        a, b, c = map(int, input().split())
        if c <= le:
            g1[a - 1, b - 1] = c
            g1[b - 1, a - 1] = c

    fw1 = floyd_warshall(g1, directed=False)

    g2 = 1000 * np.zeros((n, n))
    g2[fw1 <= le] = 1

    fw2 = floyd_warshall(g2, directed=False)

    q = int(input())
    res_list = [-1] * q
    for i in range(q):
        s, t = map(int, input().split())
        res = fw2[s - 1, t - 1]
        if res <= n:
            res_list[i] = int(res - 1)

    for r in res_list:
        print(r)
示例#3
0
文件: C.py 项目: yosho-18/AtCoder
def isOK(x):
    g2 = [[INF for j in range(n + 1)] for i in range(n + 1)]

    for i in range(h):
        for j in range(w):
            for dx, dy in dd:
                nx = j + dx
                ny = i + dy
                if 0 <= nx < w and 0 <= ny < h:
                    if s[i][j] == "." or s[i][j] == "S" or s[i][j] == "G":
                        if s[ny][nx] == "." or s[ny][nx] == "S" or s[ny][
                                nx] == "G":
                            g2[i * w + j][ny * w + nx] = 1
                            g2[ny * w + nx][i * w + j] = 1
                        else:
                            g2[i * w + j][ny * w + nx] = x
                            g2[ny * w + nx][i * w + j] = 1
                    else:
                        if s[ny][nx] == "." or s[ny][nx] == "S" or s[ny][
                                nx] == "G":
                            g2[i * w + j][ny * w + nx] = 1
                            g2[ny * w + nx][i * w + j] = x
                        else:
                            g2[i * w + j][ny * w + nx] = x
                            g2[ny * w + nx][i * w + j] = x

    cost = floyd_warshall(csr_matrix(g2))

    if cost[start][goal] < t:
        return 0
    elif cost[start][goal] > t:
        return 1
    else:
        return 2
示例#4
0
def isomap_generator(K, dataset):
    #K is the number of nearest nieghbours
    X = dataset
    #Create the Distance matrix of the dataset.
    D = distance_Matrix(dataset)
    index = D.argsort()
    #Create neighbours that are the index for the sorted K euclidan closest neighbours.
    neighbours = index[:, :K + 1]
    #Create a new distance matrix with only the K euclidian closest neighbours, the rest are set to infinity.
    H = np.ones((X.shape[0], X.shape[0]), dtype='float') * np.inf
    for i in range(X.shape[0]):
        H[i, neighbours[i, :]] = D[i, neighbours[i, :]]
    #Use the floyd Warshall algorithm to find the closest neighbors.
    D_graph = floyd_warshall(H)**2
    #Same as for the MDS
    J = np.identity(D_graph.shape[0]) - (1 / (D_graph.shape[0])) * (np.ones(
        (D_graph.shape[0], D_graph.shape[0])))
    B = -(1 / 2) * J.dot(D_graph**2).dot(J)
    eig_val, eig_vec = np.linalg.eigh(B)
    index = np.argsort(eig_val)
    index = np.flip(index)
    eig_vec = eig_vec[:, index]
    eig_val = eig_val[index]
    E_m = eig_vec[:, [0, 1]]
    Lambda_m = np.diag(eig_val[[0, 1]])
    X = np.dot(E_m, np.sqrt(Lambda_m))
    return X
示例#5
0
def solve():
  n,m  = (int(i) for i in input().split())
  distance = [[10**15]* n for _ in range(n)]
  L = []
  for i in range(n):
    distance[i][i] = 0
  for i in range(m):
    u,v,l = (int(i) for i in input().split())
    if u == 1:#???????????
     L.append([u,v,l])
    else:
      distance[u-1][v-1] = l
      distance[v-1][u-1] = l
    #print(distance)
    #print(L)
    
  d = floyd_warshall(distance)
  ans = 10**15
  for i in range(len(L)-1):
    for j in range(i+1,len(L)):
      ans = min(ans,L[i][2]+L[j][2]+d[L[i][1]-1][L[j][1]-1])
  if ans == 10**15:
   print("-1")
  else:
   print(int(ans))
示例#6
0
def main():
    import sys
    read = sys.stdin.buffer.read
    readline = sys.stdin.buffer.readline
    readlines = sys.stdin.buffer.readlines
    sys.setrecursionlimit(10 ** 7)

    from scipy.sparse import csr_matrix
    from scipy.sparse.csgraph import floyd_warshall

    n, m = map(int, readline().split())
    inf = float('inf')
    graph = [[inf] * (n + 1) for _ in range(n + 1)]
    for _ in range(m):
        u, v, l = map(int, readline().split())
        graph[u][v] = l
        graph[v][u] = l
    memo = []
    for i in range(1, n):
        graph[i][i] = 0
        if graph[1][i] != inf:
            memo.append((i, graph[1][i]))
        graph[1][i] = inf
    cost = floyd_warshall(csr_matrix(graph))
    ans = inf
    for idx, (i1, i2) in enumerate(memo):
        for j1, j2 in memo[idx + 1:]:
            ans = min(ans, i2 + j2 + cost[i1][j1])
    print(int(ans) if ans != inf else -1)
示例#7
0
def compute_apsp_floyd_warshall(lock, n=6, v=2, k=1):
    """Compute all-pairs shortest path matrix"""
    actions = lock.actions()[:n]

    print('Computing the adjacency matrix')
    n_states = v**n
    if n_states > 2**16 - 1:
        print('Warning: too many states for uint16: {} > {}'.format(
            n_states, 2**16 - 1))
    A = np.eye(n_states, dtype=np.uint16)

    # row = from
    # column = to
    def get_successors(lock):
        return [copy.deepcopy(lock).apply_macro(diff=a) for a in actions]

    for state in tqdm(lock.states(), total=n_states):
        state_id = get_state_id(state)
        next_states = get_successors(state)
        for next_state in next_states:
            next_state_id = get_state_id(next_state)
            A[state_id, next_state_id] = 1

    graph = csr_matrix(A)
    min_path_length = floyd_warshall(csgraph=graph,
                                     directed=True,
                                     return_predecessors=False)
    return min_path_length
示例#8
0
def write_graphs_and_distances(g, filename):

    try:
        os.remove(filename)
    except OSError:
        pass
    with open(filename, 'a') as f:

        for row in g:
            for element in row:
                f.write(str(element))
                f.write(" ")
            f.write("\n")
    try:
        os.remove(filename + "_dist")
    except OSError:
        pass
    with open(filename + "_dist", "a") as f:
        csr_g = csr_matrix(g)
        distances = floyd_warshall(csgraph=csr_g, directed=True)
        for row in distances:
            for element in row:
                f.write(str(int(element)))
                f.write(" ")
            f.write("\n")
示例#9
0
def is_disable(matrix, subset, aaa, bbb):
    if subset:
        sub_matrix = matrix[list(subset)].max(axis=0)
    else:
        sub_matrix = matrix[0]
    sp = floyd_warshall(sub_matrix)
    return any(sp[a, b] > 50 for a, b in zip(aaa, bbb))
def _calc_centers(graph, X, labelling, method='nearest'):
    """Return the new centers
    
    graph : sparse matrix
        Indicates the graph constructed from X
    X : ndarray
        Original Data
    labelling: 1d array
        The labelling of the vertices
    method : one of 'nearest', 'floyd_warshall', 'erosion'
        Method to calculate the new centers
    """
    size = graph.shape[0]
    centers = np.zeros(size)
    
    max_label = int(np.max(labelling))
    for label in range(1, max_label+1):
        index_vert = np.where(labelling == label)[0]
        if method == 'floyd_warshall':
            subgraph = ((graph[index_vert]).transpose())[index_vert]
            FW = floyd_warshall(subgraph, directed=False)
            ind_center = np.argmin(np.max(FW, axis=-1))
            centers[index_vert[ind_center]] = label
        elif method == 'nearest':
            mean_subgraph = np.mean(X[index_vert,:], axis=0, keepdims=True)
            dist_from_mean = np.sum((X[index_vert,:] - mean_subgraph)**2, axis = -1)
            ind_center = np.argmin(dist_from_mean.flatten())
            centers[index_vert[ind_center]] = label
        else:
            raise Exception("Only use floyd_warshall or nearest methods (for now)")
        
    return centers
示例#11
0
    def manifold_distance_matrix(self, x, K):  # [10 pts]
        """
        Args:
            x: N x D numpy array
        Return:
            dist_matrix: N x N numpy array, where dist_matrix[i, j] is the euclidean distance between points if j is in the neighborhood N(i)
            or comp_adj = shortest path distance if j is not in the neighborhood N(i).
        Hint: After creating your k-nearest weighted neighbors adjacency matrix, you can convert it to a sparse graph
        object csr_matrix (https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csr_matrix.html) and utilize
        the pre-built Floyd-Warshall algorithm (https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csgraph.floyd_warshall.html)
        to compute the manifold distance matrix.
        """

        N = x.shape[0]
        dist_matrix = np.ones((N, N)) * np.inf
        for i in range(N):
            dis = np.linalg.norm(x - np.tile(x[i], (len(x), 1)), axis=1)
            order = np.argsort(dis, axis=-1)
            dis = np.sort(dis)
            dist = dis[1:K + 1]
            order = order[1:K + 1]
            dist_matrix[i, order] = dist
            dist_matrix[order, i] = dist

        np.fill_diagonal(dist_matrix, 0)
        dist_matrix = csr_matrix(dist_matrix)
        dist_matrix = floyd_warshall(dist_matrix)
        return dist_matrix
示例#12
0
def main():
    G = nx.read_gpickle('./SJ.gpickle')
    #ox.plot_graph(G)

    T = G.copy()

    for (n,d) in T.nodes(data = True):
        d.clear()

    print(T.nodes(data = True))

    input('Press enter to continue')

    for (n1,n2,d) in T.edges(data = True):
        len_val = d['length']
        d.clear()
        d['length'] = len_val

    print(T.edges(data = True))
    #all_pairs_sp(T)

    T_adj = nx.to_scipy_sparse_matrix(T,weight = "length")

    final_dist_mtx = sc.floyd_warshall(T_adj, directed = False, unweighted = True)

    np.savetxt("./all_pairs_sp.txt", final_dist_mtx)
示例#13
0
def get_shortest_paths(grid, look_for):
    """Traverse the grid, where 0's represent holes and 1's paths, and return
    the paths to get from sources to targets, expressed in look_for in the form
    of ((start1, end1), (start2, end2)), where each 'start' and 'end'
    are coordinates of the grid in the form [x, y] pairs. It uses the
    Floyd-Warshall algorithm to find first all shortest paths and then returns
    only those in look_for"""
    # Adapted from
    # https://github.com/menpo/menpo/blob/v0.7.0/menpo/shape/graph.py
    coords = np.argwhere(grid)
    matrix = grid_to_adjacency_matrix(grid)
    _, predecessors = floyd_warshall(
        matrix, unweighted=True, return_predecessors=True
    )
    # Distance of path is always len(path) - 1 since the graph is unweighted
    paths = []
    for start_end_centers in look_for:
        start_center, end_center = sorted(start_end_centers)
        # Numpy array indices are [row, column] not [x, y]
        start = argfirst2D(coords, start_center[::-1])
        end = argfirst2D(coords, end_center[::-1])
        path = []
        if (start and end) is not None and predecessors[start, end] >= 0:
            path, step = [end], None
            while step != start:
                step = predecessors[start, path[-1]]
                path.append(step)
            path.reverse()
        # Get the coordinates for each step in path
        paths.append([(coords[step][1], coords[step][0]) for step in path])
    return paths
示例#14
0
def check(a):
    dist = floyd_warshall(a)

    for i in dist:
        if float("inf") in i:
            return True
    return False
示例#15
0
 def calculer_affichage_optimise(self, method=0):
     "Si method = 0, on utilise notre methode personnelle"
     #initialisation
     #ancienne version : D_star = calculer_D_star(floyd_warshall(self.G))
     D_star = calculer_D_star(csgraph.floyd_warshall(self.G))
     M = self.calculer_points_affichage()
     n = len(M)
     grad_e_normes, energies = [], []
     if method == 0:
         M, grad_e_normes, energies = self.fonction_gradient(
             M, D_star, self.verbose)
         if self.verbose_graphe:
             plt.plot(np.linspace(1, len(energies), len(energies)),
                      grad_e_normes)
             plt.suptitle(
                 "Evolution du gradient de l'energie en fonction des iterations"
             )
             plt.show()
     elif method == 1:
         print("M.shape = ", M.shape)
         res = opti.minimize(
             lambda m: energie_vec(m, D_star),
             vectoriser_M(M),
             options=self.options,
             method='CG'
         )  #on utilise la methode du gradient conjugue pour ameliorer la vitesse
         M = matriciser_M(res.x)
         print(res.success)
         if not res.success:
             raise Exception("La minimisation n'a pas convergé")
     else:
         raise Exception("Argument method incorrect")
     return M
def shortest_paths_nan_diag(network):
    paths = csgraph.floyd_warshall(
        network.edges[0].edges, network.edges[0].directed).astype(float)
    diag = np.lib.stride_tricks.as_strided(
        paths, (len(paths), ), ((len(paths) + 1) * paths.dtype.itemsize,))
    diag[:] = np.nan
    return paths
示例#17
0
def create_data_model():
    """Stores the data for the problem."""

    cities_map = create_cities_map()

    path_DB = cities_map.get_path('D', 'B')

    G2_data = np.array([[np.inf, np.inf, 1, np.inf, np.inf],
                        [np.inf, np.inf, 1, 2, 0],
                        [np.inf, 1, np.inf, np.inf, np.inf],
                        [np.inf, 2, np.inf, np.inf, np.inf],
                        [0, np.inf, np.inf, np.inf, np.inf]])
    G2_data = cities_map.adjacency_matrix

    G2_sparse = csgraph_from_dense(G2_data, null_value=CitiesMap.NAN_VALUE)
    dist_matrix, predecessors = floyd_warshall(csgraph=G2_sparse,
                                               directed=True,
                                               return_predecessors=True)

    data = {}

    data['distance_matrix'] = dist_matrix

    data['num_vehicles'] = 1
    data['depot'] = cities_map.city_name_to_idx(cities_map.route_city_end)
    return data, predecessors, cities_map
示例#18
0
 def findCentralTarget(self, graph):
     shortestDist = floyd_warshall(csgraph=graph,
                                   directed=False,
                                   return_predecessors=False)
     sumDist = np.sum(shortestDist, axis=0)
     centralTarget = np.argmin(sumDist)
     return centralTarget
示例#19
0
    def makeTransitive(self):
        i = 0
        while i < self.m:
            j = 0
            while j < self.n:
                if self.data[i][j] == 0:
                    self.data[i][j] = float("inf")
                j += 1
            i += 1

        tc = floyd_warshall(self.data)

        i = 0
        adds = 0

        while i < self.m:
            j = 0
            while j < self.n:
                if tc[i][j] == float("inf"):
                    self.data[i][j] = 0
                else:
                    if self.data[i][j] == float("inf"):
                        adds = adds + 1
                    self.data[i][j] = 1
                j = j + 1
            i = i + 1
        return adds
示例#20
0
    def _floyd_warshall(self, adj_mat, weights, index):
        """
        Returns matrix of shortest path weights.
        """
        res = floyd_warshall(lil_matrix(adj_mat))

        self.floyd_warshall_result[index] = res
        self.max_list[index] = (res[~np.isinf(res)]).max()
示例#21
0
    def build_shape_context(distance_matrix, points, max_distance):
        """
        :param distance_matrix:
        :param points:
        :param max_distance:
        :return:
        """
        n_angle_bins = 8
        n_distance_bins = 8
        skip_distant_points = False

        histogram = []
        max_log_distance = np.log2(max_distance)

        # Steps between assigned bins
        distance_step = max_log_distance / n_distance_bins
        angle_step = np.pi * 2 / n_angle_bins

        # Find shortest paths in distance matrix (distances as weights)
        graph = floyd_warshall(distance_matrix, directed=False)

        # Iterate all points on contour
        for i, (x0, y0) in enumerate(points):
            hist = np.zeros((n_angle_bins, n_distance_bins))
            # Calc contour tangent from previous to next point to determine angles to all other contour points
            (prev_x, prev_y) = points[i - 1]
            (next_x, next_y) = points[(i + 1) % len(points)]
            tangent = np.arctan2(next_y - prev_y, next_x - prev_x)
            # Inspect relationship to all other points (except itself)
            # direction and distance are logarithmic partitioned into n bins
            for j, (x1, y1) in enumerate(points):
                if j == i:
                    continue
                dist = graph[i, j]
                # 0 or infinity determine, that there is no path to point
                if dist != 0 and dist != np.inf:
                    log_dist = np.log2(dist)
                # Ignore unreachable points, if requested
                elif skip_distant_points:
                    continue
                # Else unreachable point is put in last dist. bin
                else:
                    log_dist = max_log_distance
                angle = (tangent - np.arctan2(y1 - y0, x1 - x0)) % (2 * np.pi)

                # Calculate bins, the inspected point belongs to
                dist_idx = int(min(np.floor(log_dist / distance_step), n_distance_bins - 1))
                angle_idx = int(min(angle / angle_step, n_angle_bins - 1))

                # Point fits into bin
                hist[angle_idx, dist_idx] += 1

            # L1 norm
            if hist.sum() > 0:
                hist = hist / hist.sum()
            histogram.append(hist.flatten())

        return np.array(histogram)
示例#22
0
def lazy_transitive_matrix(graph, name):
	filename = name + '.transitive_matrix.pickle'
	if path.isfile(filename):
		with open(filename, mode='rb') as file:
			return pickle.load(file)
	matrix = floyd_warshall(graph.to_matrix(), directed=False)
	with open(filename, mode='wb') as file:
		pickle.dump(matrix, file)
	return matrix
def graph_distance_matrix(data,epsilon=0.4,k=-1):
    """Construct a geodesic distance matrix from data in RP^n.

    Given a point cloud of data in RP^n, uses either an epsilon
    neighborhood or a k-NN algorithm to find nearby points, then builds
    a distance matrix such that nearby points have their ambient
    distance, while far away points are given the shortest path distance
    in the graph.
    
    Parameters
    ----------
    D : ndarray (n*n)
        Distance matrix to convert to an approximation of the geodesic
        distance matrix.
    epsilon : float, optional
        Radius of neighborhood when constructing graph. Default is ~pi/8.
    k : int, optional
        Number of nearest neighbors in k-NN graph. Default is -1 (i.e.
        use epsilon neighborhoods).
    normalize : bool, optional 
        Normalize the output distance matrix `Dhat` so that the maximum
        distance is the same as in the original. Default is True.

    Returns
    -------
    Dhat : ndarray
        Square distance matrix matrix of the graph. Distances are
        normalized to correspond to RP^n, i.e. Dhat is scaled so the
        maximum distance is no larger than pi/2.

    Raises
    ------
    ValueError
        If the provided value of epsilon or k is too small, the graph
        may not be connected, giving infinite values in the distance
        matrix. A value error is raised if this occurs, as the later
        algorithms do not handle infinite values smoothly.

    """

    # Use kNN. Sort twice to get nearest neighbour list.
    if k > 0:
        D_sort = np.argsort(np.argsort(D))
        A = D_sort <= k
        A = (A + A.T)/2
    # Use epsilon neighborhoods.
    else:
        A = D<epsilon
    G = csr_matrix(D*A)                   # Matrix representation of graph
    Dg = floyd_warshall(G,directed=False)     # Path-length distance matrix
    if np.isinf(np.max(Dg)):
        raise ValueError('The distance matrix contains infinite values, ' +
            'indicating that the graph is not connected. Try a larger value ' +
            'of epsilon or k.')
    Dhat = (np.max(D)/np.max(Dg))*Dg    # Normalize distances.
    return Dhat
示例#24
0
 def calculer_affichage_optimise_0(self):
     #anciennce version : D_star = calculer_D_star(floyd_warshall(self.G))
     D_star = calculer_D_star(csgraph.floyd_warshall(self.G))
     M = self.calculer_points_affichage()
     res = opti.minimize(lambda m: energie_vec(m, D_star, dim=3),
                         vectoriser_M(M),
                         options=self.options,
                         method='CG')
     M = matriciser_M(res.x, dim=3)
     return M
示例#25
0
 def tester_vitesse_iteration(self):
     M = 10
     essais = np.zeros(M)
     for i in range(M):
         M = self.calculer_points_affichage()
         D_star = calculer_D_star(csgraph.floyd_warshall(self.G))
         depart = time.time()
         calculer_gradient_energie(M, D_star)
         essais[i] = time.time() - depart
     return np.average(essais)
示例#26
0
 def iso_map(self, k_mean):
     self.k_means = k_mean
     self.nbrs_graph = kneighbors_graph(self.animals_np.T,
                                        self.k_means,
                                        mode='distance',
                                        include_self=False)
     dist_matrix = floyd_warshall(csgraph=self.nbrs_graph, directed=False)
     self.animals_k_isomap_df, lamda, vl = self.__mds_from_distance_matrix(
         False, dist_matrix)
     return self.animals_k_isomap_df, lamda, vl
 def get_distance_matrix(self, poses, radius):
     # Makes adjacency matrix and runs floyd warshall
     distances = cdist(poses, poses)
     mask = distances > np.sqrt(2) * radius
     distances[mask] = 0
     graph = distances
     dist_matrix, predecessors = floyd_warshall(csgraph=graph,
                                                directed=False,
                                                return_predecessors=True)
     return dist_matrix, predecessors
def doISOMAP(pointcloud, d, k):
    '''
    Inputs: an array like pointcloud to perform the isomap on
            d number of dimension to be reduced to
            k number of nearest connected neighbours to explore
    Output: X set of coordinates that will draw the dataset in d dimensions
    '''
    knearestMatrix = kneighbors_graph(X, k, mode='distance')
    distMatrix = floyd_warshall(knearestMatrix)

    return doMDS(distMatrix, d)
    def floyd_warshall(self, walls):
        if self.mat is None:
            self.size = len(walls[0])
            self.nrows = len(walls)
            fw_size = len(walls[0]) * len(walls)
            matrix = np.full((fw_size, fw_size),
                             fill_value=9999,
                             dtype='int16')

            matrix[0][0] = 0
            for col in range(1, len(walls[0])):
                if not walls[0][col]:
                    matrix[self._matrix_index(0, col)][self._matrix_index(
                        0, col)] = 0
                    if not walls[0][col - 1]:
                        matrix[self._matrix_index(0,
                                                  col - 1)][self._matrix_index(
                                                      0, col)] = 1
                        matrix[self._matrix_index(0, col)][self._matrix_index(
                            0, col - 1)] = 1

            for row in range(1, len(walls)):
                matrix[self._matrix_index(row, 0)][self._matrix_index(row,
                                                                      0)] = 0
                if not walls[row - 1][0] and not walls[row][0]:
                    matrix[self._matrix_index(row, 0)][self._matrix_index(
                        row - 1, 0)] = 1
                    matrix[self._matrix_index(row - 1,
                                              0)][self._matrix_index(row,
                                                                     0)] = 1

                for col in range(1, len(walls[0])):
                    matrix[self._matrix_index(row, col)][self._matrix_index(
                        row, col)] = 0
                    if not walls[row][col]:
                        if not walls[row - 1][col]:
                            matrix[self._matrix_index(row,
                                                      col)][self._matrix_index(
                                                          row - 1, col)] = 1
                            matrix[self._matrix_index(row - 1,
                                                      col)][self._matrix_index(
                                                          row, col)] = 1
                        if not walls[row][col - 1]:
                            matrix[self._matrix_index(
                                row, col - 1)][self._matrix_index(row,
                                                                  col)] = 1
                            matrix[self._matrix_index(row,
                                                      col)][self._matrix_index(
                                                          row, col - 1)] = 1
            mat, pred = floyd_warshall(matrix, False, True)
            self.mat = mat.astype(int)
            self.predecessors = pred
        return self.mat, self.predecessors
def solve():
    infinity = 10**10
    n, m, le = map(int, input().split())
    paths = np.full((n, n), infinity)
    for i in range(n):
        paths[i, i] = 0

    for _ in range(m):
        a, b, c = map(int, input().split())
        paths[a - 1, b - 1] = paths[b - 1, a - 1] = c

    paths = floyd_warshall(paths)
    paths = floyd_warshall(paths <= le)
    paths[np.isinf(paths)] = 0

    q = int(input())
    answer = []
    for _ in range(q):
        s, t = map(int, input().split())
        answer.append(int(paths[s - 1][t - 1] - 1))

    print("\n".join(map(str, answer)))
示例#31
0
def floyd(dmat, **kwdargs):
    """
    The Floyd-Wallshall algorithm for the shortest path.

    see also:
    https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csgraph.floyd_warshall.html

    :param array dmat: distance matrix
    :return: the shortest path matrix w_{ij}.
    """

    shp = floyd_warshall(csr_matrix(dmat), **kwdargs)
    return shp
示例#32
0
    def run(self, X):
        """
        Return the embedding.
        """

        #   Compute the nearest neighbor graphs
        nearestNeighbors = NearestNeighbors(n_neighbors=self.n_neighbors, algorithm='ball_tree').fit(X)
        k_neighbors_array = kneighbors_graph(X, self.n_neighbors, mode='distance').toarray()


        numNodes = k_neighbors_array.shape[0]
        # making graph symmetric
        for i in range(numNodes):
            for j in range(numNodes):
                if k_neighbors_array[j, i] <= k_neighbors_array[i, j]:
                    k_neighbors_array[i, j] = k_neighbors_array[j, i]
                else:
                    k_neighbors_array[j, i] = k_neighbors_array[i, j]

        #   Compute the all pair shortest path distance.
        dist_matrix = floyd_warshall(k_neighbors_array, directed=False)

        dist_matrix[np.isinf(dist_matrix)] = 0
        # Do MDS or learn embedding
        # MDS can also be seen as a case of Kernel PCA
        # using data dependent kernel
        # So using K = 1/2 D^2,
        # we generate projections along principal components

        kernel = dist_matrix ** 2

        kernel *= -0.5

        kernelPCA = KernelPCA(n_components=self.n_components, kernel='precomputed')

        return kernelPCA.fit_transform(kernel)
示例#33
0
    def find_mst_center(self, mst):
        """

        :param mst:
        :type mst: csr_matrix
        :return:
        :rtype: (int, int, int, csr_matrix)
        """

        distances = sp.floyd_warshall(mst, directed=False)
        segment_count, _ = distances.shape

        center = 0
        farthest_distance = np.inf
        farthest_node = 0
        for i in range(segment_count):
            distance = np.max(distances[i])
            if distance < farthest_distance:
                center = i
                farthest_distance = distance
                farthest_node = np.argmax(distances[i])

        branches = self.group_branches(mst, center)
        second_node = 0
        second_distance = 0
        for branch in branches:
            if farthest_node in branch:
                continue

            for node in branch:
                distance = distances[center, node]
                if distance > second_distance:
                    second_distance = node
                    second_node = node

        return center, farthest_node, second_node, distances
示例#34
0
        time = times[i]
        speed = speeds[i]
        endurance = endurances[i]
        distance_on_horse = 0
        for j in range(i, N-1):
            distance_on_horse += distances[j][j+1]
            if distance_on_horse > endurance:
                break
            time += distances[j][j+1] / speed
            times[j+1] = min(times[j+1], time)

    return times[-1]

f = fileinput.input()
T = int(f.readline())
for case in range(1, T+1):
    N, Q = (int(x) for x in f.readline().split())
    endurances, speeds = numpy.array([[int(x) for x in f.readline().split()] for i in range(N)]).T
    distances = numpy.array([[float(x) for x in f.readline().split()] for i in range(N)])
    distances[distances==-1] = numpy.inf
    
    distances = floyd_warshall(distances) 
    distances[distances > numpy.vstack(endurances)] = numpy.inf
    
    times = distances / numpy.vstack(speeds)
    times = floyd_warshall(times)

    starts, destinations = numpy.array([[int(x) for x in f.readline().split()] for i in range(Q)]).T
    solution = " ".join(str(times[u-1,v-1]) for u,v in zip(starts, destinations))
    print(f"Case #{case}: {solution}")