2019牛客假日团队赛3 - Roadblocks

链接:https://ac.nowcoder.com/acm/contest/945/D
来源:牛客网

Description

Bessie has moved to a small farm and sometimes enjoys returning to visit one of her best friends. She does not want to get to her old home too quickly, because she likes the scenery along the way. She has decided to take the second-shortest rather than the shortest path. She knows there must be some second-shortest path.
The countryside consists of R (1 ≤ R ≤ 100,000) bidirectional roads, each linking two of the N (1 ≤ N ≤ 5000) intersections, conveniently numbered 1…N. Bessie starts at intersection 1, and her friend (the destination) is at intersection N.
The second-shortest path may share roads with any of the shortest paths, and it may backtrack i.e., use the same road or intersection more than once. The second-shortest path is the shortest path whose length is longer than the shortest path(s) (i.e., if two or more shortest paths exist, the second-shortest path is the one whose length is longer than those but no longer than any other path).

Input

Line 1: Two space-separated integers: N and R
Lines 2…R+1: Each line contains three space-separated integers: A, B, and D that describe a road that connects intersections A and B and has length D (1 ≤ D ≤ 5000)

Output

Line 1: The length of the second shortest path between node 1 and node N
示例1

Input Sample

4 4
1 2 100
2 4 200
2 3 250
3 4 100

Output Sample

450

说明
Two routes: 1 -> 2 -> 4 (length 100+200=300) and 1 -> 2 -> 3 -> 4 (length 100+250+100=450)

解题思路

求次短路:从两头用dijkstra求出最短路,得到两个数组,遍历一遍所有的边,从每条边(u,v)中,找到所有满足 dis1[u]+EDGE(u,v)+dis2[v] > minDis(起点到终点的最短距离)条件下的最小值,即使解

AC Code

/*
 * Copyright (c) 2019 Ng Kimbing, HNU, All rights reserved. May not be used, modified, or copied without permission.
 * @Author: Ng Kimbing, HNU.
 * @LastModified:2019-06-25 T 10:43:37.961 +08:00
 */
package ACMProblems.QianDaoTi;

import java.util.*;

import static ACMProblems.ACMIO.*;

/*
 * 链接:https://ac.nowcoder.com/acm/contest/945/D
 * 来源:牛客网
 *
 * ## Description
 * Bessie has moved to a small farm and sometimes enjoys returning to visit one of her best friends. She does not want to get to her old home too quickly, because she likes the scenery along the way. She has decided to take the second-shortest rather than the shortest path. She knows there must be some second-shortest path.
 * The countryside consists of R (1 ≤ R ≤ 100,000) bidirectional roads, each linking two of the N (1 ≤ N ≤ 5000) intersections, conveniently numbered 1..N. Bessie starts at intersection 1, and her friend (the destination) is at intersection N.
 * The second-shortest path may share roads with any of the shortest paths, and it may backtrack i.e., use the same road or intersection more than once. The second-shortest path is the shortest path whose length is longer than the shortest path(s) (i.e., if two or more shortest paths exist, the second-shortest path is the one whose length is longer than those but no longer than any other path).
 * ## Input
 * Line 1: Two space-separated integers: N and R
 * Lines 2..R+1: Each line contains three space-separated integers: A, B, and D that describe a road that connects intersections A and B and has length D (1 ≤ D ≤ 5000)
 *
 * ## Output
 * Line 1: The length of the second shortest path between node 1 and node N
 * 示例1
 * ## Input Sample
 * >4 4
 * 1 2 100
 * 2 4 200
 * 2 3 250
 * 3 4 100
 *
 * ## Output Sample
 * >450
 * >
 * **说明**
 * Two routes: 1 -> 2 -> 4 (length 100+200=300) and 1 -> 2 -> 3 -> 4 (length 100+250+100=450)
 */
public class SecondShortest {
    static class VertexNode {
        private int id;
        private int weight;

        public VertexNode(int id, int weight) {
            this.id = id;
            this.weight = weight;
        }

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public int getWeight() {
            return weight;
        }

        public void setWeight(int weight) {
            this.weight = weight;
        }

        @Override
        public boolean equals(Object obj) {
            return this.id == ((VertexNode) obj).id;
        }
    }

    static class Edge {
        int from;
        int to;
        int weight;

        public Edge(int from, int to, int weight) {
            this.from = from;
            this.to = to;
            this.weight = weight;
        }

        @Override
        public String toString() {
            return "(" + from + " -> " + to + ", " + weight + ")";
        }
    }

    private static int vertexNum;
    private static ArrayList<VertexNode>[] lists;

    /**
     * Add one edge into the graph. The weight will be changed if the edge already exists.
     *
     * @param a      Start
     * @param b      End
     * @param weight The weight of the edge from a to b
     */
    public static void addEdge(int a, int b, int weight) {
        assert a < vertexNum && b < vertexNum;
        lists[a].add(new VertexNode(b, weight));
        lists[b].add(new VertexNode(a, weight));
        edges[index++] = new Edge(a, b, weight);
        edges[index++] = new Edge(b, a, weight);
    }

    private static int[] dijkstra(int a, int b) {
        assert a < vertexNum && b < vertexNum;
        int[] dis = new int[vertexNum];
        boolean[] visited = new boolean[vertexNum];
        // The heap used to find the closest vertex.
        PriorityQueue<VertexNode> q = new PriorityQueue<>(vertexNum, Comparator.comparingInt(VertexNode::getWeight));
        //initialize
        q.add(new VertexNode(a, 0));
        Arrays.fill(dis, 0x3f3f3f3f);
        dis[a] = 0;
        while (!q.isEmpty()) {
            // Current vertex.
            VertexNode v = q.poll();
            int currID = v.getId();
            //Mark as visited.
            visited[currID] = true;
            //for each neighbor
            for (VertexNode dest : lists[currID]) {
                //if there is a shorter path
                if (!visited[dest.getId()] && dis[currID] + dest.getWeight() < dis[dest.getId()]) {
                    dis[dest.getId()] = dis[currID] + dest.getWeight();
                    q.add(new VertexNode(dest.getId(), dis[dest.getId()]));
                }
            }
        }
        return dis;
    }

    static Edge[] edges;
    static int index = 0;

    @SuppressWarnings("unchecked")
    public static void main(String[] args) throws Exception {
        setStream(System.in);
        vertexNum = nextInt();
        int edgeNum = nextInt();
        edges = new Edge[edgeNum * 2];
        lists = new ArrayList[vertexNum];
        for (int i = 0; i < vertexNum; ++i)
            lists[i] = new ArrayList<>();
        for (int i = 0; i < edgeNum; ++i) {
            int a = nextInt() - 1;
            int b = nextInt() - 1;
            int weight = nextInt();
            addEdge(a, b, weight);
        }
        int[] dis1 = dijkstra(0, vertexNum - 1);
        int[] dis2 = dijkstra(vertexNum - 1, 0);
        int minDis = dis1[vertexNum - 1];
        int currMin = Integer.MAX_VALUE;
        for (Edge edge : edges) {
            int from = edge.from;
            int to = edge.to;
            int weight = edge.weight;
            int foo = dis1[from] + dis2[to] + weight;
            if (foo > minDis)
                currMin = Math.min(foo, currMin);
        }
        System.out.println(currMin);
    }
}

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
题目要求:给定一个二叉树和一个整数target,找出所有从根节点到叶子节点路径之和等于target的路径。 解题思路:可以使用深度优先搜索(DFS)的方法来解决该问题。首先定义一个辅助函数来进行递归搜索,该辅助函数的参数包括当前节点、当前路径、当前路径的和以及目标和。在搜索过程中,需要维护一个数组来保存当前节点到根节点的路径。搜索过程如下: 1. 如果当前节点为空,则返回。 2. 将当前节点的值添加到当前路径中。 3. 将当前节点的值累加到当前路径的和中。 4. 如果当前节点是叶子节点,且当前路径的和等于目标和,则将当前路径添加到结果中。 5. 递归地搜索当前节点的左子树和右子树,并传递更新后的当前路径和当前路径的和。 最后,在主函数中调用辅助函数,并返回结果即可。 以下是题目的完整代码实现: ```python class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def pathSum(root, target): def dfs(node, path, path_sum, target, res): if not node: return path.append(node.val) path_sum += node.val if not node.left and not node.right: # 当前节点是叶子节点 if path_sum == target: res.append(path[:]) # 注意需要复制一份path,否则会出现问题 dfs(node.left, path, path_sum, target, res) dfs(node.right, path, path_sum, target, res) path.pop() # 回溯到父节点,去掉当前节点 path_sum -= node.val res = [] dfs(root, [], 0, target, res) return res ``` 这样就能找出所有满足路径和等于目标和的路径了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值