uri online judge 3145 solution in c++
Sure! Here is a response that provides a solution in C++ for the URI Online Judge problem 3145, along with explanations for each step:
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
int n;
std::cin >> n;
std::vector<int> numbers(n);
for (int i = 0; i < n; i++) {
std::cin >> numbers[i];
}
std::sort(numbers.begin(), numbers.end());
int minDistance = numbers[1] - numbers[0];
for (int i = 2; i < n; i++) {
minDistance = std::min(minDistance, numbers[i] - numbers[i - 1]);
}
std::cout << minDistance << std::endl;
return 0;
}
Explanation:
The code begins by including the necessary header files:
<iostream>
for input/output operations,<vector>
for using the vector container, and<algorithm>
for using thestd::sort
andstd::min
functions.The
main
function is defined, which will be the entry point of the program.A variable
n
is declared to store the number of elements in the input array.The value of
n
is read from the standard input usingstd::cin
.A vector
numbers
is declared to store the input elements.A loop is used to read
n
numbers from the standard input and store them in thenumbers
vector.The
std::sort
function is called to sort the elements in thenumbers
vector in ascending order.A variable
minDistance
is initialized with the difference between the second and first elements of the sortednumbers
vector. This will serve as the initial minimum distance between consecutive elements.Another loop is used to iterate over the sorted
numbers
vector, starting from the third element (index 2).In each iteration of the loop, the difference between the current element and the previous element is calculated. If this difference is smaller than the current minimum distance, it becomes the new minimum distance.
Finally, the minimum distance is printed to the standard output using
std::cout
.The
main
function returns 0 to indicate successful program execution.
This solution reads an array of numbers, sorts them, and then finds the minimum difference between consecutive elements. It uses the std::sort
function to sort the elements and a loop to calculate the minimum difference. The final result is printed to the standard output.