882. Reachable Nodes In Subdivided Graph
题目链接
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的更多相关文章
- [LeetCode] 882. Reachable Nodes In Subdivided Graph 细分图中的可到达结点
Starting with an undirected graph (the "original graph") with nodes from 0 to N-1, subdivi ...
- [Swift]LeetCode882. 细分图中的可到达结点 | Reachable Nodes In Subdivided Graph
Starting with an undirected graph (the "original graph") with nodes from 0 to N-1, subdivi ...
- [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 ...
- All LeetCode Questions List 题目汇总
All LeetCode Questions List(Part of Answers, still updating) 题目汇总及部分答案(持续更新中) Leetcode problems clas ...
- leetcode hard
# Title Solution Acceptance Difficulty Frequency 4 Median of Two Sorted Arrays 27.2% Hard ...
- Swift LeetCode 目录 | Catalog
请点击页面左上角 -> Fork me on Github 或直接访问本项目Github地址:LeetCode Solution by Swift 说明:题目中含有$符号则为付费题目. 如 ...
- 【LeetCode】堆 heap(共31题)
链接:https://leetcode.com/tag/heap/ [23] Merge k Sorted Lists [215] Kth Largest Element in an Array (无 ...
- 【Leetcode周赛】从contest-91开始。(一般是10个contest写一篇文章)
Contest 91 (2018年10月24日,周三) 链接:https://leetcode.com/contest/weekly-contest-91/ 模拟比赛情况记录:第一题柠檬摊的那题6分钟 ...
- [Algorithms] Graph Traversal (BFS and DFS)
Graph is an important data structure and has many important applications. Moreover, grach traversal ...
随机推荐
- Markdown初步使用
一.兼容 HTML Markdown 的理念是,能让文档更容易读.写和随意改.HTML 是一种发布的格式,Markdown 是一种书写的格式.就这样,Markdown 的格式语法只涵盖纯文本可以涵盖的 ...
- JVM内存管理之GC算法精解(复制算法与标记/整理算法)
本次LZ和各位分享GC最后两种算法,复制算法以及标记/整理算法.上一章在讲解标记/清除算法时已经提到过,这两种算法都是在此基础上演化而来的,究竟这两种算法优化了之前标记/清除算法的哪些问题呢? 复制算 ...
- xshell连接kali
连接出现错误,连接不上去,看到一篇文章可以使用,https://blog.csdn.net/yemaxq/article/details/78171241
- (转)Inno Setup入门(十一)——完成安装后执行某些程序
本文转载自:http://blog.csdn.net/yushanddddfenghailin/article/details/17250901 有些时候我们的程序虽然能够很好的完成安装,但是程序的配 ...
- Jetty实战(杂七杂八)
最近开始选择JETTY作为服务器了,乘这现在空闲点学习了些JETTY的部署知识,原来她真的跟TOMCAT很类似,先总结如下: 部署应用方法(下载好jetty); 方法一: 直接将应用的 war包放在j ...
- PorterDuff.Mode
参考:http://weishu.me/2015/09/23/Xfermode-in-android/ Sa = Source alphaDa = Dest alphaSc = Source colo ...
- Web应用层协议---HTTP
处于协议栈顶层的应用层协议定义了运行在不同端系统的应用程序进程如何相互传递报文.定义内容如下: 1.交换的报文类型.请求报文和响应报文. 2.各种报文类型的语法,如报文中的各个字段及这这些字段是如何描 ...
- laravel5中添加自定义函数
laravel里面我们很多朋友不知道把自定义函数放在哪儿.我们的应用里经常会有一些全局都可能会用的函数,我们应该怎么放置它会比较好呢?现在匀们为大家准备了laravel放置函数的规范. 1. 创建文件 ...
- css选择器30种
CSS 选择器是一种模式,用于选择需要添加样式的元素.平时使用最多也是最简单的就是 #id..class 和标签选择器,在 CSS 中还有很多更加强大更加灵活的选择方式,尤其是在 CSS3 中,增加了 ...
- python 之 itertools模块
官方:https://yiyibooks.cn/xx/python_352/library/itertools.html 参考: https://blog.csdn.net/neweastsun/ar ...