#include #include #include #include #include // Globals for convenience in a contest setting int N, M; std::vector heights; std::vector> adj; /** * @brief Checks if a path exists from a start node to an end node using only * hills within the specified height range. * @param start_node The starting hill (always 1). * @param end_node The destination hill (always 2). * @param min_h The minimum allowed height on the path. * @param max_h The maximum allowed height on the path. * @return True if a path exists, false otherwise. */ bool can_reach(int start_node, int end_node, int min_h, int max_h) { // A path is impossible if the start or end hills are outside the allowed height range. if (heights[start_node] < min_h || heights[start_node] > max_h || heights[end_node] < min_h || heights[end_node] > max_h) { return false; } std::queue q; std::vector visited(N + 1, false); q.push(start_node); visited[start_node] = true; while (!q.empty()) { int u = q.front(); q.pop(); if (u == end_node) { return true; // Path found } // Explore neighbors for (int v : adj[u]) { if (!visited[v] && heights[v] >= min_h && heights[v] <= max_h) { visited[v] = true; q.push(v); } } } return false; // No path found } int main() { // Fast I/O std::ios_base::sync_with_stdio(false); std::cin.tie(NULL); std::cin >> N >> M; heights.resize(N + 1); std::set unique_heights_set; for (int i = 1; i <= N; ++i) { std::cin >> heights[i]; unique_heights_set.insert(heights[i]); } adj.resize(N + 1); for (int i = 0; i < M; ++i) { int u, v; std::cin >> u >> v; adj[u].push_back(v); adj[v].push_back(u); } // Create a sorted vector of unique heights from the set std::vector sorted_heights(unique_heights_set.begin(), unique_heights_set.end()); int k = sorted_heights.size(); int min_diff = -1; // Two-pointer/sliding window approach int j = 0; // Right pointer of the window for (int i = 0; i < k; ++i) { // Left pointer of the window int h_low = sorted_heights[i]; // j does not reset. Continue expanding the window [h_low, h_high] // by increasing j until a connection is found. while (j < k) { int h_high = sorted_heights[j]; if (can_reach(1, 2, h_low, h_high)) { // Found the smallest h_high for this h_low. int current_diff = h_high - h_low; if (min_diff == -1 || current_diff < min_diff) { min_diff = current_diff; } // We are done with this i. Break from the inner loop // and shrink the window from the left by incrementing i. break; } // If no connection, we must increase h_high by advancing the right pointer. j++; } // Optimization: If j ran off the end, no more connections are possible for any subsequent i. if (j == k) { break; } } std::cout << min_diff << std::endl; return 0; }