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 ...
随机推荐
- 1.远程仓库的使用(github)
1.登录Github,新建一个仓库(远程仓库) (1)使用Github账号密码登录 (2)点击+旁边的小三角,选择new repository--输入repository name--点击create ...
- RK3288 查看ddr频率
转载请注明出处:https://www.cnblogs.com/lialong1st/p/8515135.html RK3288 查看 ddr 当前频率的方式有两种,第一种是通过 adb 查看,第二种 ...
- 搭建基于hyperledger fabric的联盟社区(九) --检索状态数据库
一.启动elasticsearch服务 官网下载压缩包解压,进入bin目录启动: ./elasticsearch 通过ip访问 localhost:9200,可以看到如下信息 { name: &quo ...
- Python Socke
回射 SERVER #!/usr/bin/python3 #_*_ coding:utf- _*_ import socket,os,time import socketserver import t ...
- css怎么设置2个div同行,第一个固定宽度,第二个占满剩余的部分
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- 【转】用Jmeter制造测试数据
在平时的测试过程中,肯定会有碰到需要一批大量的数据的情况,如果这些数据本身没有太多的要求,或者说需求比较简单,可以通过简单的参数化实现的,推荐用Jmeter来造数据. 限制: Jmeter只能支持ja ...
- java内存占用问题(一)
Nocturne 2012-12-24 java数组内存占用问题. 30 Contact[] ca = new Contact[10]; while(x<10){ ca[x]=new ...
- Python文件操作,with open as追加文本内容实例
最常见的读写操作 import re with open('/Users/Mr.Long/Desktop/data.txt', 'w') as f: f.write('hello world') 就这 ...
- 将eclipse的编码改成UTF-8,默认是GBK
第一步.在菜单栏选择“window“----preference----General-----Workspace 选中Workspace 在右边窗口中找到Text file encoding ...
- 超详细的php用户注册页面填写信息完整实例(附源码)
这篇文章主要介绍了一个超详细的php用户注册页面填写信息完整实例,内容包括邮箱自动匹配.密码强度验证以及防止表单重复等,小编特别喜欢这篇文章,推荐给大家. 注册页面是大多数网站必备的页面,所以很有必要 ...