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 ...
随机推荐
- 安装 LAMP
卸载 并安装 MYSQL rpm -qa | grep mysql rpm -e mysql-libs--.el6.x86_64 -.el6.x86_64 cd /usr/local/src/ wge ...
- 笔记本设置wifi热点并抓包
现在很多人喜欢蹭wifi热点,这里演示一下怎么利用笔记本设置wifi热点来钓鱼.本机是win10操作系统. 一.设置笔记wifi热点:右键点击右下角网络图标 -> 打开“网络和Internet设 ...
- 基于Oracle的EntityFramework的WEBAPI2的实现(四)——自动生成在线帮助文档
打开我们项目中的Area文件夹,正常情况下,我们会发现已经有了一个名字叫做[HelpPage]的区域(Area),这个区域是vs帮助我们自动建立的,它是一个mvc(不是webapi),它有普通的Con ...
- 用活Firewalld防火墙之direct
原文地址:http://www.excelib.com/article/294/show 学生在前面已经给大家介绍过了Firewalld中direct的作用,使用他可以直接使用iptables.ip6 ...
- Log4j配置详解之log4j.xml
Log4j配置详解之log4j.xml Log4J的配置文件(Configuration File)就是用来设置记录器的级别.存放器和布局的,它可接key=value格式的设置或xml格式的设置信息. ...
- Java中的GetOpt操作
在shell工具中,有专门的getopt函数,使用方法如下所示: while getopts "d:t:vh" opt; do case "${opt}" in ...
- Go - 指针简介 与 ++/--运算符以及控制语句
指针 Go 语言中,对于指针有一些特殊约束: 1. 不在支持 “->” 符号,所有的指针使用“.” 来操作指针对象的成员变量 2. 指针的默认值为 “nil” ++ 与 -- 作为语句而非表达式 ...
- 将 .NET 任务作为 WinRT 异步操作公开
转自:http://blogs.msdn.com/b/windowsappdev_cn/archive/2012/06/22/net-winrt.aspx 在博文深入探究 Await 和 WinRT ...
- 堆、栈、free
转自:http://codeup.org/archives/212 http://bbs.bccn.net/thread-82212-1-1.html http://www.cppblog.com/o ...
- sql sever数据库常用的执行语句
--使用master数据库use master --创建数据库文件create database 数据库名字 on( name=, --逻辑名称 filename= .ndf, --数据文件物理路径名 ...