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:

  1. The code begins by including the necessary header files: <iostream> for input/output operations, <vector> for using the vector container, and <algorithm> for using the std::sort and std::min functions.

  2. The main function is defined, which will be the entry point of the program.

  3. A variable n is declared to store the number of elements in the input array.

  4. The value of n is read from the standard input using std::cin.

  5. A vector numbers is declared to store the input elements.

  6. A loop is used to read n numbers from the standard input and store them in the numbers vector.

  7. The std::sort function is called to sort the elements in the numbers vector in ascending order.

  8. A variable minDistance is initialized with the difference between the second and first elements of the sorted numbers vector. This will serve as the initial minimum distance between consecutive elements.

  9. Another loop is used to iterate over the sorted numbers vector, starting from the third element (index 2).

  10. 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.

  11. Finally, the minimum distance is printed to the standard output using std::cout.

  12. 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.