题目链接

https://leetcode.com/contest/weekly-contest-96/problems/reachable-nodes-in-subdivided-graph/

解题思路

1)题目要求,经过m步后,可以到达的点,等价于求有多少点距离起点的最短距离小于等于m,即这是一个单源最短路径问题,使用djstra算法

复杂度

时间 o(eloge)

空间复杂度o(e). e为边数

本解决方案的注意点

1)计数时,节点和边上的点要分开计数,防止重复计算节点

2)使用优先队列保存边,会有重复的节点出现,需要过滤下

java代码

class Node {
public int src;
public int move;
public Node(int src, int move) {
this.src = src;
this.move = move;
}
} public class Solution {
public int reachableNodes(int[][] edges, int M, int N) {
Map<Integer, Map<Integer, Integer>> graph = new HashMap<>();
for (int i = 0; i < N; i++) {
graph.put(i, new HashMap<>());
}
Map<Integer, Boolean> visited = new HashMap<>();
Queue<Node> pq = new PriorityQueue<>((a, b) -> (a.move - b.move)); //build graph
for (int[] v : edges) {
graph.get(v[0]).put(v[1], v[2]);
graph.get(v[1]).put(v[0], v[2]);
} int result = 0;
Node head = new Node(0, 0);
pq.offer(head);
while (!pq.isEmpty()) {
Node cur = pq.peek();
pq.poll();
int src = cur.src;
int move = cur.move;
if (null != visited.get(src)) continue;
visited.put(src, true);
++result; for (int id : graph.get(src).keySet()) {
int dst = id;
int weight = graph.get(src).get(dst);
int nextMove = move + weight + 1;
if (null != visited.get(dst)) {
result += Math.min(M - move, graph.get(src).get(dst));
} else {
if (nextMove > M) {
result += M - move;
graph.get(dst).put(src, graph.get(dst).get(src) - (M - move));
} else {
result += weight;
graph.get(dst).put(src, 0);
Node next = new Node(dst, nextMove);
pq.offer(next);
}
}
}
} return result;
}
}

c++代码

class Node {
public:
int src;
int move;
Node(int a, int b) {
this->src = a;
this->move = b;
}
}; class MyCmp {
public:
bool operator() (const Node& l, const Node& r) {
return l.move > r.move;
}
}; class Solution {
public:
int reachableNodes(vector<vector<int>>& edges, int M, int N) {
unordered_map<int, unordered_map<int, int>> graph;
unordered_map<int, bool> visited;
priority_queue<Node, vector<Node>, MyCmp> pq; //build graph
for (vector<int> v : edges) {
graph[v[0]][v[1]] = v[2];
graph[v[1]][v[0]] = v[2];
} int result = 0;
Node head(0, 0);
pq.push(head); while (!pq.empty()) {
Node cur = pq.top();
pq.pop();
int src = cur.src;
int move = cur.move;
if (move > M) break; //may be duplicated
if (visited[src]) continue;
visited[src] = true;
result++; //travel array
for (auto& it : graph[src]) {
int dst = it.first;
int weight = it.second;
int nextMove = move + weight + 1;
if (visited[dst]) {
result += min(M - move, graph[src][dst]);
} else {
if (nextMove > M) {
result += M - move;
graph[dst][src] -= M - move;
} else {
result += weight;
graph[dst][src] = 0;
Node next(dst, nextMove);
pq.push(next);
}
}
}
} return result;
}
};

python代码

class Solution(object):
def reachableNodes(self, edges, M, N):
"""
:type edges: List[List[int]]
:type M: int
:type N: int
:rtype: int
"""
# hashmap
graph = {}
visited = {}
pq = []
result = 0
for i in range(N):
graph[i] = {} for i, j, l in edges:
graph[i][j] = graph[j][i] = l # print graph heapq.heappush(pq, (0, 0))
while pq:
move, src = heapq.heappop(pq)
# print move, "==", src
if move > M:
break if src in visited:
continue visited[src] = 1
result = result + 1 for dst in graph[src]:
weight = graph[src][dst]
next_move = move + weight + 1
if dst in visited:
result += min(M - move, graph[src][dst])
else:
if next_move > M:
result += M - move
graph[dst][src] -= M - move
else:
result += weight
graph[dst][src] = 0
heapq.heappush(pq, (next_move, dst)) return result

882. Reachable Nodes In Subdivided Graph的更多相关文章

  1. [LeetCode] 882. Reachable Nodes In Subdivided Graph 细分图中的可到达结点

    Starting with an undirected graph (the "original graph") with nodes from 0 to N-1, subdivi ...

  2. [Swift]LeetCode882. 细分图中的可到达结点 | Reachable Nodes In Subdivided Graph

    Starting with an undirected graph (the "original graph") with nodes from 0 to N-1, subdivi ...

  3. [CareerCup] 4.2 Route between Two Nodes in Directed Graph 有向图中两点的路径

    4.2 Given a directed graph, design an algorithm to find out whether there is a route between two nod ...

  4. All LeetCode Questions List 题目汇总

    All LeetCode Questions List(Part of Answers, still updating) 题目汇总及部分答案(持续更新中) Leetcode problems clas ...

  5. leetcode hard

    # Title Solution Acceptance Difficulty Frequency     4 Median of Two Sorted Arrays       27.2% Hard ...

  6. Swift LeetCode 目录 | Catalog

    请点击页面左上角 -> Fork me on Github 或直接访问本项目Github地址:LeetCode Solution by Swift    说明:题目中含有$符号则为付费题目. 如 ...

  7. 【LeetCode】堆 heap(共31题)

    链接:https://leetcode.com/tag/heap/ [23] Merge k Sorted Lists [215] Kth Largest Element in an Array (无 ...

  8. 【Leetcode周赛】从contest-91开始。(一般是10个contest写一篇文章)

    Contest 91 (2018年10月24日,周三) 链接:https://leetcode.com/contest/weekly-contest-91/ 模拟比赛情况记录:第一题柠檬摊的那题6分钟 ...

  9. [Algorithms] Graph Traversal (BFS and DFS)

    Graph is an important data structure and has many important applications. Moreover, grach traversal ...

随机推荐

  1. Centos下 yum方式安装LAMP

    首先安装apache    centos可以直接yum安装apache . 配置网易163 yum源  http://www.cnblogs.com/carbon3/p/5635403.html 一. ...

  2. php分页类 可直接调用

    <?php /** * 分页类 * @author xyy * 调用分页实例 $subPages=new SubPages(数据总条数);//实例化分页类 * //$subPages->s ...

  3. JVM调优总结(这个总结得比较全面)

    堆大小设置 JVM 中最大堆大小有三方面限制:相关操作系统的数据模型(32-bt还是64-bit)限制:系统的可用虚拟内存限制:系统的可用物理内存限制.32位系统下,一般限制在1.5G~2G:64为操 ...

  4. Jetty实战(杂七杂八)

    最近开始选择JETTY作为服务器了,乘这现在空闲点学习了些JETTY的部署知识,原来她真的跟TOMCAT很类似,先总结如下: 部署应用方法(下载好jetty); 方法一: 直接将应用的 war包放在j ...

  5. 1095 Cars on Campus

    题意:给出N量车的车牌号,进出的时间,进/出状态.然后给出若干个查询,要求计算在每一查询时刻校园内停着的汽车数量,最后输出这一天中停放时间最长的车辆(若车不止一辆,则按字典序输出)以及停放时间.注:查 ...

  6. css选择器30种

    CSS 选择器是一种模式,用于选择需要添加样式的元素.平时使用最多也是最简单的就是 #id..class 和标签选择器,在 CSS 中还有很多更加强大更加灵活的选择方式,尤其是在 CSS3 中,增加了 ...

  7. 【学习笔记】FFT

    1.内容 由于noble_太懒 不想写了 非常好的博客: https://www.cnblogs.com/rvalue/p/7351400.html http://www.cnblogs.com/ca ...

  8. java后台读取配置文件中key与value -----demo2

    /** * * @Title: getValue * @Description: TODO * @param key * @return import java.util.Properties; * ...

  9. Linux 调优方案--ulimit命令

    可以用ulimit -a 来显示当前的各种用户进程限制.下面把某linux用户的最大进程数设为10000个:     ulimit -u 10240     对于需要做许多 socket 连接并使它们 ...

  10. Git学习之常用的命令

    配置git git config --global user.name "你的github用户名" git config --global user.email "你的G ...