码迷,mamicode.com
首页 > 其他好文 > 详细

787. Cheapest Flights Within K Stops

时间:2020-08-05 10:29:42      阅读:73      评论:0      收藏:0      [点我收藏+]

标签:any   add   wiki   arraylist   route   arrays   put   nec   fill   

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

787. Cheapest Flights Within K Stops

标签:any   add   wiki   arraylist   route   arrays   put   nec   fill   

原文地址:https://www.cnblogs.com/wentiliangkaihua/p/13437693.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!