C++ code to get shortest distance from circular stations



Suppose we have two numbers s and t, and another array D with n elements. The circle line of the Dreamland subway has n different stations. We know the distances between all pairs of neighboring stations: D[i] is the distance between station i and i+1, and D[n-1] is the distance between (n-1) and 0th station. We have to find shortest distance from s to t.

So, if the input is like s = 1; t = 3; D = [2, 3, 4, 9], then the output will be 5.

Steps

To solve this, we will follow these steps −

n := size of D Define an array arr of size (n + 1), and fill with 0 for initialize i := 1, when i <= n, update (increase i by 1), do:    arr[i] := D[i - 1]    sum1 := sum1 + arr[i] if s > t, then:    swap s and t for initialize i := s, when i < t, update (increase i by 1), do:    sum2 := sum2 + arr[i] return minimum of sum2 and (sum1 - sum2)

Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h> using namespace std; int solve(int s, int t, vector<int> D){    int n = D.size(), sum1 = 0, sum2 = 0;    vector<int> arr(n + 1, 0);    for (int i = 1; i <= n; i++){       arr[i] = D[i - 1];       sum1 += arr[i];    }    if (s > t)       swap(s, t);    for (int i = s; i < t; i++)       sum2 += arr[i];    return min(sum2, sum1 - sum2); } int main(){    int s = 1;    int t = 3;    vector<int> D = { 2, 3, 4, 9 };    cout << solve(s, t, D) << endl; }

Input

1, 3, { 2, 3, 4, 9 }

Output

5
Updated on: 2022-03-29T11:56:52+05:30

479 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements