zoukankan      html  css  js  c++  java
  • 787. Cheapest Flights Within K Stops

    https://leetcode.com/problems/cheapest-flights-within-k-stops/description/

    DFS (slow)

    class Solution {
    public:
        vector<vector<pair<int,int>>> v;     // city: <connected city, price>
        vector<bool> visited;
        int res = INT_MAX;
        
        int findCheapestPrice(int n, vector<vector<int>>& flights, int src, int dst, int K) {
            v = vector<vector<pair<int,int>>>(n);
            visited = vector<bool>(n, false);
            
            for (const auto& flight : flights)
                v[flight[0]].push_back( { flight[1], flight[2] });
            
            visited[src] = true;
            dfs(n, src, dst, K+1, 0);
            return res == INT_MAX ? -1 : res;
        }
        
        void dfs(int n, int cur, int dst, int K, int cost) {
            if (cur == dst) {
                res = min(res, cost);
                return;
            }
            if (cost >= res)    return;     // if cost >= res, no point to search further
            if (K == 0) return;
            
            for (const auto& pCityPrice : v[cur]) {
                if (!visited[pCityPrice.first]) {
                    visited[cur] = true;
                    dfs(n, pCityPrice.first, dst, K-1, cost + pCityPrice.second);
                    visited[cur] = false;
                }
            }
        }
    };

    BFS (seems not able to use BFS as below, we may have to record each path. Looks like paths in BFS is not independent, we can't use BFS. In this case, if A->B->C and A->C, we are not able to determine cost[C] unless we keep track the path to C. Then we may use DFS directly.)

    class Solution {
    public:
        int findCheapestPrice(int n, vector<vector<int>>& flights, int src, int dst, int K) {
            vector<vector<pair<int,int>>> v = vector<vector<pair<int,int>>>(n);
            vector<int> cost = vector<int>(n, -1);
            
            for (const auto& flight : flights)
                v[flight[0]].push_back( { flight[1], flight[2] });
            
            queue<int> q;
            q.push(src);
            cost[src] = 0;
            
            int stop = 0;
            while (!q.empty()) {
                if (stop++ > K)
                    break;
                
                int qsz = q.size();
                while (qsz-- > 0) {
                    int cur = q.front(); q.pop();
                    for (const auto& pCityPrice : v[cur]) {
                        int curDest = pCityPrice.first;
                        if (cost[curDest] == -1 || cost[curDest] > cost[cur] + pCityPrice.second) {
                            q.push(curDest);
                            cost[curDest] = cost[cur] + pCityPrice.second;
                        }
                    }
                }
            }
            return cost[dst];
        }
    };

    Expand stops from src.

    class Solution {
    public:
        int findCheapestPrice(int n, vector<vector<int>>& flights, int src, int dst, int K) {
            vector<vector<pair<int,int>>> v = vector<vector<pair<int,int>>>(n);
            
            for (const auto& flight : flights)
                v[flight[0]].push_back( { flight[1], flight[2] });
            
            vector<vector<int>> dp(n, vector<int>(K+1, INT_MAX));
            
            for (const auto& pCityPrice : v[src]) {
                int curDest = pCityPrice.first;
                int curPrice = pCityPrice.second;
                dp[curDest][0] = min(dp[curDest][0], curPrice);
            }
            for (int k = 1; k <= K; k++) {
                for (int i = 0; i < n; i++) {
                    if (dp[i][k-1] == INT_MAX)   continue;
                    for (const auto& pCityPrice : v[i]) {
                        int curDest = pCityPrice.first;
                        int curPrice = pCityPrice.second;
                        dp[curDest][k] = min(dp[curDest][k], dp[i][k-1] + curPrice);
                    }
                }
            }
            int res = INT_MAX;
            for (int k = 0; k <= K; k++)
                res = min(res, dp[dst][k]);
            return res == INT_MAX ? -1 : res;
        }
    };

    Think backward, expand stops from dst.

    class Solution {
    public:
        int findCheapestPrice(int n, vector<vector<int>>& flights, int src, int dst, int K) {
            vector<int> bestfrom(n, INT_MAX);     // Current best from n to dst
            
            for (const auto& flight : flights) {        // non-stop from each city to dst
                if (flight[1] == dst)
                    bestfrom[flight[0]] = min(bestfrom[flight[0]], flight[2]);
            }
            // from each city to dst with one more stop.
            // say we know bestfrom[A] is reachable, now if we find price[B->A] + bestfrom[A] < bestfrom[B],
            // we find a better route from B to dst.
            for (int k = 1; k <= K; k++) {              
                for (const auto& flight : flights) {
                    if (bestfrom[flight[1]] != INT_MAX)
                        bestfrom[flight[0]] = min(bestfrom[flight[0]], bestfrom[flight[1]] + flight[2]);
                }
            }
            return bestfrom[src] == INT_MAX ? -1 : bestfrom[src];
        }
    };
  • 相关阅读:
    log4j:WARN No appenders could be found for logger (org.springframework.web.context.ContextLoader).
    警告: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:fhcq-oa' did not find a matching property.
    SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
    Maven 仓库之阿里云镜像配置
    HashMap 在 Java1.7 与 1.8 中的区别
    MySQL 相关知识细节及解析
    JS 如何准确获取当前页面URL网址信息
    i++ 和 ++i
    常见浏览器兼容性问题与解决方案(面试题目)
    面试题目简单整理-完善中
  • 原文地址:https://www.cnblogs.com/JTechRoad/p/8978075.html
Copyright © 2011-2022 走看看