题目链接

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. 什么是YARN

    YARN的核心组件: 1)ResourceManager,扮演Master角色(和HDFS的nameNode很像)主要用于资源分配:RM有两个子组件,分别是Scheduler(Capacity Sch ...

  2. 微信卡券领取页面提示签名错误,微信卡券JSAPI签名校验工具对比签名一模一样,cardExt扩展字段有问题

    一.领券页面错误 二.给到前端的数据 三.根据给前端的额数据做签名校验 四.给前端的签名和校验的签名一致(这一步能判断签名没有问题,基本可以判断是前端调用微信接口时拼接的数据有问题) 五.以下是微信的 ...

  3. 1-3 superset数据模型

    在models.py中大部分的class对应数据库中的表,那么我们就从AuditMixinNullable这个类开始我们的模型解析. AuditMixin:这个类是FAB(Flask  AppBuil ...

  4. 网站建设之高速WEB的实现

    1.此文目的 漂亮的色彩.绚丽的动画在输入网址后便能呈现在你的眼前.互联网无可否认已经融入了我们的生活. 我们可以山寨出iPhone却很难有属于自己独特的理念关于事物的思想和心脏. 互联网是现实.艺术 ...

  5. emacs之配置etags-select

    etags-select比自带的etags定位的更好 ~/emacsConfig/etags-select-setting.el (require 'etags-select) (global-set ...

  6. HDOJ5883(欧拉路)

    The Best Path Time Limit: 9000/3000 MS (Java/Others)    Memory Limit: 65535/32768 K (Java/Others)Tot ...

  7. TransportClient操作详解

    Elasticsearch JAVA操作有三种客户端: 1.TransportClient 2.JestClient 3.RestClient 还有种是2.3中有的NodeClient,在5.5.1中 ...

  8. Java字符代码中干掉制表符、回车符和换行符

    Java字符代码中干掉制表符.回车符和换行符 代码片段: String sql = StringUtils.trim(sql).replaceAll("[\\r\\n\\t]",& ...

  9. (转) docker跨主机 macvlan 网络配置

    原文链接 https://github.com/alfredhuang211/study-docker-doc/blob/master/docker%E8%B7%A8%E4%B8%BB%E6%9C%B ...

  10. python学习——练习题(7)

    """ 题目:将一个列表的数据复制到另一个列表中. """ import copy def validate(a, b): "&q ...