Flight Discount

Your task is to find a minimum-price flight route from Syrjala to Metsala. You have one discount coupon, using which you can halve the price of any single flight during the route. However, you can only use the coupon once.

Example:

Input:  n = 3, m = 4, edges = {{1, 2, 3}, {2, 3, 1}, {1, 3, 7}, {2, 1, 5}}
Output: 2

Approach

C++

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

const long long inf = 10000000000000000LL;

const long long N = 100005;
long long vis[N];
long long dis1[N], dis2[100005];

void dijkistrasAlgorithm(long long slong long dis[],
                         vector<pair<long longlong long>> adj[])
{
    priority_queue<pair<long longlong long>> q;

    //initialize with very big number
    for (int i = 1i < Ni++)
        dis[i] = inf;
    dis[s] = 0;
    q.push({0s});

    //mark visited array as not visited
    memset(vis0sizeof(vis));

    //iterate till the end of queue
    while (!q.empty())
    {

        long long a = q.top().second;

        //remove from the queue
        q.pop();

        //if already visited
        if (vis[a])
            continue;

        //mark as visited
        vis[a] = 1;
        for (auto edge : adj[a])
        {
            long long b = edge.first;
            long long w = edge.second;

            //relaxation
            if (dis[a] + w < dis[b])
            {
                dis[b] = dis[a] + w;
                q.push({-dis[b], b});
            }
        }
    }
}

long long flightDiscount(int nint m,
                         vector<vector<long long>> &edges)
{

    vector<pair<long longlong long>> adj1[n + 1];
    vector<pair<long longlong long>> adj2[n + 1];

    for (long long i = 0i < mi++)
    {
        long long a = edges[i][0];
        long long b = edges[i][1];
        long long w = edges[i][2];

        adj1[a].push_back({bw});
        adj2[b].push_back({aw});
    }
    dijkistrasAlgorithm(1dis1adj1);
    dijkistrasAlgorithm(ndis2adj2);
    long long mn = inf;
    for (auto edge : edges)
    {
        long long a = edge[0];
        long long b = edge[1];
        long long w = edge[2];
        mn = min(mndis1[a] + dis2[b] + w / 2);
    }
    return mn;
}
int main()
{

    long long n = 3m = 4;

    vector<vector<long long>> edges = {{123},
                                       {231},
                                       {137},
                                       {215}};

    cout << flightDiscount(nmedges<< "\n";

    return 0;
}


No comments:

Post a Comment