zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    Mac下配置phpredis扩展
    PHP 面向对象中常见关键字使用(final、static、const和instanceof)
    PHP null常量和null字节的区别
    PHP关于时区问题
    C++指针的操作和运算(转)
    浅谈C++中指针和引用的区别者之间的区别和用法(转)
    rails Rendering Text 用法
    MySQL“慢SQL”定位
    数组循环移位问题
    core文件问题
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/13437693.html
Copyright © 2011-2022 走看看