#K83987. Sorting with Swap Threshold
Sorting with Swap Threshold
Sorting with Swap Threshold
You are given an array of distinct integers and a threshold d. You are allowed to swap two elements only if the absolute difference between them is at most d (i.e. \(|a_i - a_j| \le d\)). Your task is to determine whether it is possible to sort the array in non-decreasing order using only these allowed swaps.
Input Format: The input consists of three lines. The first line contains an integer n, representing the number of elements in the array. The second line contains n space-separated integers, representing the array. The third line contains a single integer d, the swap threshold.
Output Format: Output a single line containing "YES" if the array can be sorted using allowed swaps, or "NO" otherwise.
Note: The solution should use an algorithm based on union-find (disjoint set) to group indices that can be mutually swapped if they satisfy the condition \(|a_i - a_j| \le d\), then verify if the sorted order can be obtained by rearranging values within each group.
inputFormat
The first line contains an integer n (\(1 \le n \le 10^5\)), the number of elements in the array.
The second line contains n space-separated integers \(a_1, a_2, \ldots, a_n\) representing the array. All elements are distinct.
The third line contains an integer d (\(0 \le d \le 10^9\)), the maximum allowed absolute difference for a swap.
outputFormat
Output a single line: "YES" if the array can be sorted into non-decreasing order using the allowed swaps; otherwise, output "NO".
## sample5
4 2 3 1 5
3
YES
</p>