Tour

Walter White is on a tour to sell meth. There are N cities.

Each city has a id between 1 and N (both inclusive).

You are given a cost matrix.

In cost matrix, the jth element in the ith row denotes the cost of travelling between cities with id i and j.

cost[i][j]=cost[j][i] and cost[i][i]=0

Given the path taken by Walter, print the cost of traveling.

Walter is at the city with id 1 right now.

Example:

Input: n = 3, str = {"delhi", "bengaluru", "hyderabad"}, arr = {{0, 10, 20}, {10, 0, 55}, {20, 55, 0}}, q = 4, queries = {"bengaluru", "delhi", "hyderabad", "bengaluru"}
Output: 95

Approach

C++

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

long long tour(long long nvector<stringstr,
               vector<vector<long long>> arrlong long q,
               vector<stringqueries)
{

    map<stringlong longmp;

    for (long long i = 0i < ni++)
    {

        mp[str[i]] = i;
    }

    long long i = 0j = 0;
    long long ans = 0;

    for (long long k = 0k < qk++)
    {
        string s = queries[k];
        j = mp[s];
        ans += arr[i][j];
        i = j;
    }

    return ans;
}

int main()
{
    long long n = 3;

    vector<stringstr = {"delhi",
                          "bengaluru",
                          "hyderabad"};

    vector<vector<long long>> arr = {{01020},
                                     {10055},
                                     {20550}};

    long long q = 4;

    vector<stringqueries = {"bengaluru",
                              "delhi",
                              "hyderabad",
                              "bengaluru"};
    cout << tour(nstrarrqqueries<< "\n";

    return 0;
}


No comments:

Post a Comment