我是靠谱客的博主 诚心月饼,最近开发中收集的这篇文章主要介绍886. Reachable Nodes In Subdivided Graph,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

Starting with an undirected graph (the "original graph") with nodes from 0 to N-1, subdivisions are made to some of the edges.

The graph is given as follows: edges[k] is a list of integer pairs (i, j, n) such that (i, j) is an edge of the original graph,

and n is the total number of new nodes on that edge. 

Then, the edge (i, j) is deleted from the original graph, n new nodes (x_1, x_2, ..., x_n) are added to the original graph,

and n+1 new edges (i, x_1), (x_1, x_2), (x_2, x_3), ..., (x_{n-1}, x_n), (x_n, j) are added to the original graph.

Now, you start at node 0 from the original graph, and in each move, you travel along one edge. 

Return how many nodes you can reach in at most M moves.

 

Example 1:

Input: edges = [[0,1,10],[0,2,1],[1,2,2]], M = 6, N = 3
Output: 13
Explanation: 
The nodes that are reachable in the final graph after M = 6 moves are indicated below.

Example 2:

Input: edges = [[0,1,4],[1,2,6],[0,2,8],[1,3,1]], M = 10, N = 4
Output: 23

 

Note:

  1. 0 <= edges.length <= 10000
  2. 0 <= edges[i][0] < edges[i][1] < N
  3. There does not exist any i != j for which edges[i][0] == edges[j][0] and edges[i][1] == edges[j][1].
  4. The original graph has no parallel edges.
  5. 0 <= edges[i][2] <= 10000
  6. 0 <= M <= 10^9
  7. 1 <= N <= 3000
  8. A reachable node is a node that can be travelled to using at most M moves starting from node 0.

单源最短路径,注意不要重复计算

class Solution:
def reachableNodes(self, edges, M, N):
"""
:type edges: List[List[int]]
:type M: int
:type N: int
:rtype: int
"""
import heapq
a=[[-1 for _ in range(N)] for _ in range(N)]
for s,t,n in edges: a[s][t]=a[t][s]=n
res=0
pq=[]
vis=[False for _ in range(N)]
heapq.heappush(pq, (-M,0))
while pq:
m,s = heapq.heappop(pq)
m=-m
if vis[s]: continue
vis[s]=True
res+=1
for i in range(N):
if a[s][i]<0: continue
if m>a[s][i] and not vis[i]: heapq.heappush(pq, (-(m-a[s][i]-1),i))
# some node between s and i are used
a[i][s] -= min(m, a[s][i])
res+=min(m, a[s][i])
return res

 

最后

以上就是诚心月饼为你收集整理的886. Reachable Nodes In Subdivided Graph的全部内容,希望文章能够帮你解决886. Reachable Nodes In Subdivided Graph所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(40)

评论列表共有 0 条评论

立即
投稿
返回
顶部