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  t, then:
   swap s and t
for initialize i := s, when i 

Example

Let us see the following implementation to get better understanding −

#include 
using namespace std;
int solve(int s, int t, vector D){
   int n = D.size(), sum1 = 0, sum2 = 0;
   vector arr(n + 1, 0);
   for (int i = 1; i  t)
      swap(s, t);
   for (int i = s; i  D = { 2, 3, 4, 9 };
   cout 

Input

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

Output

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

525 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements