
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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
- Related Articles
- Shortest Distance from All Buildings in C++
- JAVA Program to Calculate Shortest Distance from Center of the Circle to Chord
- Find Shortest distance from a guard in a Bankin Python
- Shortest Distance to Target Color in C++
- Shortest Word Distance II in C++
- Shortest Word Distance III in C++
- Shortest distance between objects in JavaScript
- C++ Program to find the Shortest Distance to a character
- Corresponding shortest distance in string in JavaScript
- Shortest Path to Get All Keys in C++
- Program to find distance of shortest bridge between islands in Python
- Program to Find the Shortest Distance Between Two Points in C++
- How to get current country code from Network provider in android?
- How to get current postal code from Network provider in android?
- How to get the colour name from colour code in R?

Advertisements