Flight Routes

Your task is to find the k shortest flight routes from Syrjälä to Metsälä. A route can visit the same city several times.

Note that there can be several routes with the same price and each of them should be considered.

Example:

Input: n = 4, m = 6, k = 3, arr = {{1, 2, 1}, {1, 3, 3}, {2, 3, 2}, {2, 4, 6}, {3, 2, 8}, {3, 4, 1}}
Output: 4 4 7

Approach

C++

#include <bits/stdc++.h>
using namespace std;

void flightRoutes(long long nlong long mlong long k,
                  vector<vector<long long>> &arr)
{
    vector<pair<long longlong long>> adj[n + 1];
    for (long long i = 0i < mi++)
    {
        long long a = arr[i][0]b = arr[i][1];
        long long w = arr[i][2];

        adj[a].push_back({bw});
    }
    priority_queue<pair<long longlong long>> q;
    q.push({01});
    long long vis[n + 1] = {0};
    while (!q.empty() && vis[n] < k)
    {
        long long a = q.top().second;
        long long d = q.top().first;
        q.pop();
        vis[a]++;
        if (a == n)
            cout << -d << " ";
        if (vis[a] <= k)
        {
            for (auto [bw] : adj[a])
            {

                q.push({d - wb});
            }
        }
    }
}
int main()
{
    long long n = 4m = 6k = 3;

    vector<vector<long long>> arr = {{121},
                                     {133},
                                     {232},
                                     {246},
                                     {328},
                                     {341}};

    flightRoutes(nmkarr);

    return 0;
}


No comments:

Post a Comment