Shortest Routes II

There are n cities and m roads between them. Your task is to process q queries where you have to determine the length of the shortest route between two given cities.

Example:

Input: n = 4, m = 3, q = 5, edges = {{1, 2, 5}, {1, 3, 9}, {2, 3, 3}},queries = {{1, 2}, {2, 1}, {1, 3}, {1, 4}, {3, 2}}

Output:

5 5 8 -1 3

Approach:

C++

#include <bits/stdc++.h>
using namespace std;
#define INF 1000000000000000000
int main()
{
    long long int n = 4m = 3q = 5;
    vector<vector<long long int>> edges = {{125},
                                           {139},
                                           {233}};

    vector<vector<long long>> queries = {{12},
                                         {21},
                                         {13},
                                         {14},
                                         {32}};
    long long int dist[n + 1][n + 1];
    for (long long int i = 1i <= ni++)
    {
        for (long long int j = 1j <= nj++)
        {
            if (i != j)
                dist[i][j] = INF;
            else
                dist[i][j] = 0;
        }
    }
    for (int i = 0i < mi++)
    {
        long long int a = edges[i][0];
        long long int b = edges[i][1];
        long long int w = edges[i][2];

        dist[a][b] = min(wdist[a][b]);
        dist[b][a] = min(wdist[b][a]);
    }
    for (long long int k = 1k <= nk++)
    {
        for (long long int i = 1i <= ni++)
        {
            for (long long int j = 1j <= nj++)
            {
                if (dist[i][j] > dist[i][k] + dist[k][j])
                {
                    dist[i][j] = dist[i][k] + dist[k][j];
                }
            }
        }
    }
    for (int i = 0i < qi++)
    {
        long long int l = queries[i][0]r = queries[i][1];

        if (dist[l][r] == INF)
            cout << -1 << "\n";
        else
            cout << dist[l][r<< "\n";
    }
    return 0;
}


No comments:

Post a Comment