• 787. Cheapest Flights Within K Stops


    There are n cities connected by m flights. Each flight starts from city u and arrives at v with a price w.

    Now given all the cities and flights, together with starting city src and the destination dst, your task is to find the cheapest price from src to dst with up to k stops. If there is no such route, output -1.

    Example 1:
    Input: 
    n = 3, edges = [[0,1,100],[1,2,100],[0,2,500]]
    src = 0, dst = 2, k = 1
    Output: 200
    Explanation: 
    The graph looks like this:
    

    The cheapest price from city 0 to city 2 with at most 1 stop costs 200, as marked red in the picture.
    Example 2:
    Input: 
    n = 3, edges = [[0,1,100],[1,2,100],[0,2,500]]
    src = 0, dst = 2, k = 0
    Output: 500
    Explanation: 
    The graph looks like this:
    

    The cheapest price from city 0 to city 2 with at most 0 stop costs 500, as marked blue in the picture.
    

    Constraints:

    • The number of nodes n will be in range [1, 100], with nodes labeled from 0 to n - 1.
    • The size of flights will be in range [0, n * (n - 1) / 2].
    • The format of each flight will be (src, dst, price).
    • The price of each flight will be in the range [1, 10000].
    • k is in the range of [0, n - 1].
    • There will not be any duplicated flights or self cycles.
    class Solution {
      public int findCheapestPrice(int n, int[][] flights, int src, int dst, int K)
        {
            int[] cost=new int[n];
            Arrays.fill(cost,Integer.MAX_VALUE);
            cost[src]=0;
            for(int i=0;i<=K;i++)
            {
                int[] temp= Arrays.copyOf(cost,n);
                for(int[] f: flights)
                {
                    int curr=f[0],next=f[1],price=f[2];
                    if(cost[curr]==Integer.MAX_VALUE)
                        continue;
                    temp[next]=Math.min(temp[next],cost[curr]+price);
                }
                cost=temp;
            }
            return cost[dst]==Integer.MAX_VALUE?-1:cost[dst];
        }
    }

    src 到 dst 之间up to k stops,在bellman-ford算法中,relax一次可以(有可能)增长一次path,所以我们总共需要relax 1 + k次。

    注意:bellman-ford中relax N-1次是因为从起始点到所有其他点最多能延长N-1,使最长路径path为N

    引用:“

    BF runs V-1 iterations since that's the longest possible path from src to dest - one that uses every vertex. In this problem, since the longest path is given as K+1, you only need to run it that many iterations.

    See https://en.wikipedia.org/wiki/Bellman–Ford_algorithm
    "After i repetitions of for loop... if there is a path from s to u with at most i edges, then Distance(u) is at most the length of the shortest path from s to u with at most i edges."

    Bellman-ford初始化除了自己外cost全是Max_VALUE

    class Solution {
    public int findCheapestPrice(int n, int[][] flights, int src, int dst, int K)
        {
            Map<Integer,List<int[]>> map=new HashMap<>();
            for(int[] i:flights)
            {
                map.putIfAbsent(i[0],new ArrayList<>());
                map.get(i[0]).add(new int[]{i[1],i[2]});
            }
            int step=0;
            Queue<int[]> q=new LinkedList<>();
            q.offer(new int[]{src,0});
            int ans=Integer.MAX_VALUE;
            while(!q.isEmpty())
            {
                int size=q.size();
                for(int i=0;i<size;i++)
                {
                    int[] curr=q.poll();
                    if(curr[0]==dst)
                        ans=Math.min(ans,curr[1]);
                    if(!map.containsKey(curr[0]))
                        continue;
                    for(int[] f:map.get(curr[0]))
                    {
                        if(curr[1]+f[1]>ans)      //Pruning
                            continue;
                        q.offer(new int[]{f[0],curr[1]+f[1]});
                    }
                }
                if(step++>K)
                    break;
            }
            return ans==Integer.MAX_VALUE?-1:ans;
        }
    }

    BFS

  • 相关阅读:
    請問各位大大,我要將listview顯示的縮圖加入到listview2,請問該如何做呢
    一个可设置窗口透明属性的控件,可让窗口透明、半透明
    laravel he stream or file "..laravel-2019-02-14.log" could not be opened: failed to open stream: Permission denied
    每日学习-20190721
    linux centos无法删除网站根目录下的.user.ini解决办法
    laravel在使用Composer安装插件时要求输入授权用户名密码解决办法
    Centos7 日志查看工具
    Centos7 Putty SSH密钥登录
    阿里云Centos7用putty ssh链接掉线
    阿里云 centos 无法执行moodle cron
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/13437693.html
Copyright © 2020-2023  润新知