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

原文地址:https://www.cnblogs.com/ctrlzhang/p/9485036.html

时间: 2024-10-15 21:46:22

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, subdivisions are made to some of the edges. The graph is given as follows:?edges[k]?is a list of integer pairs?(i, j, n)?such that?(i, j)?is an edge of the origin

[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 nodes. LeetCode和CareerCup中关于图的题都不是很多,LeetCode中只有三道,分别是Clone Graph 无向图的复制,Course Schedule 课程清单 和 Course Schedule II 课程清单之二.目前看来CareerCup中有关图的题在第四章中仅此一道,这是

【LeetCode】堆 heap(共31题)

[23] Merge k Sorted Lists [215] Kth Largest Element in an Array (无序数组中最小/大的K个数) 给了一个无序数组,可能有重复数字,找到第 k 个最大的元素并且返回这个元素值. 题解:直接用直接用个堆保存数组中最大的 K 个数.时间复杂度是 O(NlogK). 1 //时间复杂度是 O(NlogK), 用堆辅助. 2 class Solution { 3 public: 4 int findKthLargest(vector<int>

Route Between Two Nodes in Graph (java)

Given a directed graph, design an algorithm to find out whether there is a route between two nodes. Example Given graph: A----->B----->C \ | \ | \ | \ v ->D----->E for s = B and t = E, return true for s = D and t = C, return false /** * Defini

[Algorithms] Graph Traversal (BFS and DFS)

Graph is an important data structure and has many important applications. Moreover, grach traversal is key to many graph algorithms. There are two systematic ways to traverse a graph, breadth-first search (BFS) and depth-frist search (DFS). Before fo

POJ1419 Graph Coloring(最大独立集)(最大团)

Graph Coloring Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 4926   Accepted: 2289   Special Judge Description You are to write a program that tries to find an optimal coloring for a given graph. Colors are applied to the nodes of the

HDU4647:Another Graph Game(贪心)

Problem Description Alice and Bob are playing a game on an undirected graph with n (n is even) nodes and m edges. Every node i has its own weight Wv, and every edge e has its own weight We. They take turns to do the following operations. During each

UVA Graph Coloring

主题如以下: Graph Coloring  You are to write a program that tries to find an optimal coloring for agiven graph. Colors are applied to the nodes of the graph and the only availablecolors are black and white. The coloring of the graph is called optimalif a

uva 193 Graph Coloring(回溯)

uva 193 Graph Coloring You are to write a program that tries to find an optimal coloring for a given graph. Colors are applied to the nodes of the graph and the only available colors are black and white. The coloring of the graph is called optimal if